RazorDocs Search
API Reference

Core

Namespaces

Type

ModuleDependencyBuilder

Source

A builder used to discover and register module dependencies recursively.

Remarks

ModuleDependencyBuilder is intended for the single-threaded startup composition phase. It is not thread-safe; callers must synchronize access if multiple threads could call AddModule{T} or enumerate Modules concurrently.

Method

AddModule

ModuleDependencyBuilder AddModule<T>() Source

Adds a module of type T and its dependencies to the builder.

Type Parameters

  • TThe module type to add. It must have a public parameterless constructor.

Returns

The current ModuleDependencyBuilder instance.

Remarks

The module instance is created with the new() constraint and pre-registered before IAppSurfaceModule.RegisterDependentModules(ModuleDependencyBuilder) runs. That pre-registration prevents infinite recursion for cyclic module graphs and means dependency callbacks observe already-created module instances. Prefer manual registration or a factory-based composition root when module construction needs dependency injection, runtime arguments, or externally owned disposable resources. If dependency registration throws, the newly created module remains in the builder, so later AddModule{T} calls for that same type are no-ops against a partial graph. Treat registration failures as fatal for the current builder instance.

Property

Modules

IEnumerable<IAppSurfaceModule> Modules { get; } Source

Gets the collection of registered modules.

Remarks

Modules are keyed by concrete type and added once. Enumeration order is implementation-dependent and should not be treated as a stable contract. A module is visible in Modules before its IAppSurfaceModule.RegisterDependentModules(ModuleDependencyBuilder) callback registers children.

Type

StartupContext

Source

Provides context and configuration during the application startup process.

Parameters

  • ArgsCommand-line arguments provided to the application.
  • RootModuleThe root module of the application.
  • ApplicationNameOptional user-facing display label for product surfaces. Defaults to the root module assembly name when not provided. This value does not control Generic Host/static web asset manifest identity.
  • EnvironmentProviderOptional provider for environment information.
  • CustomRegistrationsOptional custom service registrations.
Method

GetDependencies

IReadOnlyList<IAppSurfaceModule> GetDependencies() Source

Gets the list of modules that the application depends on.

Returns

A read-only list of dependent modules.

Property

DependenciesRegistered

bool DependenciesRegistered { get; set; } Source

Gets or sets whether startup dependency registration has already run for this context.

Remarks

Defaults to false. AppSurfaceStartup{TRootModule} sets this to true after framework and root-module dependencies are registered so repeated startup-time calls are no-ops for the same StartupContext. This state is intended for single-threaded startup composition and is not safe for concurrent writes.

Property

OverrideEntryPointAssembly

Assembly? OverrideEntryPointAssembly { get; set; } Source

Gets or sets an assembly that should override both application discovery and host manifest identity.

Remarks

Set this when a test or custom host needs AppSurface to scan a different assembly for commands, MVC parts, or Aspire components, or when static web asset manifest identity must be pinned to a specific assembly.

Property

ConsoleOutputMode

ConsoleOutputMode ConsoleOutputMode { get; set; } Source

Gets or sets how console-oriented apps should present command output relative to ambient host lifecycle diagnostics.

Remarks

The default value is ConsoleOutputMode.Default, which preserves the standard Generic Host behavior. Console startups can switch to ConsoleOutputMode.CommandFirst when command output should remain the primary user-facing console experience. Non-console apps can ignore this setting.

Property

RootModuleAssembly

Assembly RootModuleAssembly { get; } Source

Gets the assembly that contains the root module.

Property

EntryPointAssembly

Assembly EntryPointAssembly { get; } Source

Gets the assembly used for application-owned type discovery.

Remarks

AppSurface uses this assembly to discover application-owned commands, MVC application parts, Aspire components, and similar extensibility hooks. By default it stays aligned with the root module assembly so cross-assembly test runners and shared hosts do not accidentally scan the outer process entry assembly. Set OverrideEntryPointAssembly when a host intentionally wants discovery to come from a different assembly.

Property

HostIdentityAssembly

Assembly HostIdentityAssembly { get; } Source

Gets the assembly whose name should be written into the Generic Host environment.

Remarks

ASP.NET static web assets resolve runtime manifests through Microsoft.Extensions.Hosting.IHostEnvironment.ApplicationName. When OverrideEntryPointAssembly is not provided, AppSurface falls back to Assembly.GetEntryAssembly() here so the host environment tracks the real executable surface rather than the root module's assembly. When no process entry assembly is available, the root module assembly remains the defensive fallback.

Property

EnvironmentProvider

IEnvironmentProvider EnvironmentProvider { get; } Source

Gets the environment provider for the application.

Property

IsDevelopment

bool IsDevelopment { get; } Source

Gets a value indicating whether the current environment is development.

Property

ApplicationName

string ApplicationName { get; init; } Source

Gets the user-facing name of the application.

Remarks

This value is intended for product surfaces such as generated OpenAPI titles, command output, and other places where callers need a readable application label. It is intentionally separate from HostApplicationName, which must stay aligned with the assembly identity used by the .NET Generic Host and ASP.NET static web asset manifest discovery.

Property

HostApplicationName

string HostApplicationName { get; } Source

Gets the assembly-backed application identity assigned to Microsoft.Extensions.Hosting.IHostEnvironment.ApplicationName.

Remarks

ASP.NET static web assets resolve runtime manifests by host application name. Custom display names should not be written into the host environment because they can point static web asset discovery at a non-existent manifest. By default AppSurface uses the process entry assembly when one is available; override OverrideEntryPointAssembly when a test or custom host needs to select a different manifest identity. This host identity is intentionally separate from EntryPointAssembly, which still drives application-owned type discovery.

Type

PathUtils

Source

Provides utility methods for operations on file and directory paths.

Method

FindRepositoryRoot

2 overloads
string FindRepositoryRoot(string startPath) Source

Locates the nearest ancestor directory (starting at startPath) that contains a `.git` directory or file, effectively identifying the repository root.

Parameters

  • startPathThe path from which to begin searching upward for a repository root; may refer to a file or directory.

Returns

The full path of the nearest ancestor directory containing a `.git` directory or file, or the original startPath if none is found.

Exceptions

  • ArgumentExceptionThrown when startPath is null, empty, or consists only of whitespace.
string FindRepositoryRoot(string startPath, ILogger logger) Source

Locates the nearest ancestor directory (starting at startPath) that contains a `.git` directory or file, effectively identifying the repository root.

Parameters

  • startPathThe path from which to begin searching upward for a repository root; may refer to a file or directory.
  • loggerLogger for diagnostic warnings when repository-root discovery has to recover from a path that does not exist.

Returns

The full path of the nearest ancestor directory containing a `.git` directory or file, or the original startPath if none is found.

Exceptions

  • ArgumentExceptionThrown when startPath is null, empty, or consists only of whitespace.
  • ArgumentNullExceptionThrown when logger is null.
Method

GetExistingFileDirectory

string GetExistingFileDirectory(string startPath) Source

Resolves the containing directory for an existing file path used by repository-root discovery.

Parameters

  • startPathA non-empty path already known to reference an existing file.

Returns

The normalized containing directory for startPath.

Exceptions

  • ArgumentExceptionThrown when the normalized file path does not yield a containing directory.

Remarks

FindRepositoryRootCore calls GetExistingFileDirectory only after File.Exists(string?) has accepted startPath as an existing file. The method normalizes the value with Path.GetFullPath(string) so relative file paths are canonicalized before returning the directory portion from Path.GetDirectoryName(string?). If normalization cannot produce a containing directory, ArgumentException.ThrowIfNullOrEmpty(string?, string?) throws to surface the broken existing-file invariant instead of silently probing from an unrelated fallback path.

Type

IAppSurfaceStartup

Source

Defines the entry point for starting and running an AppSurface application.

Remarks

IAppSurfaceStartup.CreateHostBuilder is called before IAppSurfaceStartup.RunAsync. The implementation configures an IHostBuilder, but the framework or caller owns starting, stopping, and disposing the built IHost. CreateHostBuilder must not start the host or perform blocking I/O and should be idempotent unless documented otherwise. RunAsync may be called once per StartupContext, should remain asynchronous, and should honor cancellation exposed by the configured host.

Method

CreateHostBuilder

IHostBuilder CreateHostBuilder(StartupContext context) Source

Creates and configures the IHostBuilder for the application.

Parameters

  • contextThe startup context containing configuration and arguments.

Returns

A configured host builder.

Method

RunAsync

Task RunAsync(StartupContext context) Source

Runs the application asynchronously using the provided startup context.

Parameters

  • contextThe startup context for the application.

Returns

A task that represents the asynchronous run operation.

Type

IEnvironmentProvider

Source

Provides information about the application's environment and configuration variables.

Remarks

Use IEnvironmentProvider for DI-friendly, testable environment access in application and core code. Prefer direct System.Environment access only in infrastructure adapters, one-off scripts, or the implementation of this contract. IsDevelopment must stay consistent with Environment and should be derived by comparing the environment name to Development with ordinal ignore-case semantics. GetEnvironmentVariable implementations should be side-effect-free, preserve OS-specific variable name behavior, and document invalid-name handling when they do not delegate directly to System.Environment.

Method

GetEnvironmentVariable

string? GetEnvironmentVariable(string name, string? defaultValue = null) Source

Gets the value of an environment variable.

Parameters

  • nameThe exact environment variable name to query.
  • defaultValueThe value to return when the variable is unset.

Returns

The variable value, an empty string when explicitly set empty, or defaultValue when unset.

Remarks

Implementations should be side-effect-free and preserve the platform's environment-name behavior: Windows is generally case-insensitive, while Unix-like systems are case-sensitive. Return defaultValue only when the variable is unset and the underlying lookup returns null; an explicitly empty variable is a real empty string and should not be replaced by the default.

Property

Environment

string Environment { get; } Source

Gets the current environment name (e.g., "Development", "Staging", "Production").

Property

IsDevelopment

bool IsDevelopment { get; } Source

Gets a value indicating whether the current environment is "Development".

Enum

ConsoleOutputMode

Source

Describes how AppSurface console apps should balance command-owned output against ambient host lifecycle diagnostics.

Type

AppSurfaceStartup

Source

Provides a base implementation for starting and running applications with module support.

Remarks

Inherit from AppSurfaceStartup{TRootModule} when the application has a concrete root IAppSurfaceHostModule and can use the standard AppSurface host-building flow. Use a host-specific startup such as WebStartup when middleware or endpoint hooks are needed, or implement IAppSurfaceStartup directly when the host lifecycle is custom. StartupContext.ApplicationName is the AppSurface-facing label used by modules and diagnostics; StartupContext.HostApplicationName is the generic host identity applied to configuration and hosting infrastructure.

Method

GetStartupLogger

ILogger GetStartupLogger() Source

Provides an ILogger named after the concrete startup type.

Returns

An ILogger whose category name is the concrete startup type's name.

Type

AppSurfaceStartup<TRootModule>

Source

An abstract base class for initializing an AppSurface application with a specific root module.

Type Parameters

  • TRootModuleThe type of the root module for the application.

Remarks

AppSurfaceStartup{TRootModule} creates TRootModule through the new() constraint, discovers its dependencies, and lets only IAppSurfaceHostModule dependencies receive host lifecycle hooks. Plain IAppSurfaceModule dependencies participate in service registration only. Prefer this base class for console or generic-host apps; use web-specific startup types for ASP.NET Core pipeline work.

Method

RunAsync

3 overloads
Task IAppSurfaceStartup.RunAsync(StartupContext context) Source

Runs the startup sequence using the provided startup context.

Parameters

  • contextStartup configuration including application arguments, root module, and dependency/module registrations.

Returns

A task that completes when the startup sequence finishes.

Task RunAsync(string[] args) Source

Starts the application's run sequence using the specified command-line arguments.

Parameters

  • argsCommand-line arguments supplied to the application.

Returns

A task that completes when the host run finishes.

Task RunAsync(StartupContext context) Source

Runs the host configured by the provided startup context and logs lifecycle events according to the configured console output mode.

Parameters

  • contextContext containing application name, root module, dependencies, and any custom registrations used to build and configure the host.

Returns

A task that completes when the host run has finished and shutdown processing is complete.

Remarks

By default this method emits an informational shutdown log via logger.LogInformation("Run Exited - Shutting down") after host.RunAsync() completes. When StartupContext.ConsoleOutputMode is ConsoleOutputMode.CommandFirst, that shutdown log is suppressed so command-first console flows can keep help and validation output free of lifecycle noise. Logs a warning if shutdown is cancelled or does not complete in time. On an unhandled exception logs a critical error and sets Environment.ExitCode to -100.

Method

CreateHostBuilder

IHostBuilder IAppSurfaceStartup.CreateHostBuilder(StartupContext context) Source

Creates an IHostBuilder configured for the provided startup context.

Parameters

  • contextThe startup context whose application name, modules, and registrations drive host configuration.

Returns

An IHostBuilder configured according to the given context.

Method

CreateHost

IHost CreateHost(StartupContext context) Source

Builds an IHost from the host builder configured for the provided startup context.

Parameters

  • contextThe startup context that provides application name, modules, and configuration used to construct the host.

Returns

The constructed IHost.

Method

CreateHostBuilderCore

IHostBuilder CreateHostBuilderCore(StartupContext context) Source

Create and configure a host builder using values from the provided startup context.

Parameters

  • contextStartup context containing the application label, host application identity, root module, and dependencies used to configure the host builder.

Returns

A host builder configured with the context's host application identity, registered modules, and service registrations.

Method

CreateRootModule

TRootModule CreateRootModule() Source

Creates a new instance of the root module.

Returns

A new TRootModule instance.

Method

RegisterDependencies

void RegisterDependencies(StartupContext context) Source

Registers framework and root-module dependencies into the startup context once.

Parameters

  • contextStartup context whose dependency graph should be prepared.

Remarks

App-type startups normally let AppSurface call this during host-builder creation. Specialized startup lifecycles may call it earlier when they need module-derived options before building the host. For example, CLI hosts that need packaged-asset or web-option defaults before the Generic Host exists should call RegisterDependencies(context) before reading those settings.

The method adds Defaults.InternalServicesModule first, invokes IAppSurfaceModule.RegisterDependentModules(ModuleDependencyBuilder) on the root module, and then marks StartupContext.DependenciesRegistered so repeated calls are no-ops for the same context. This method is not thread-safe; access each StartupContext from a single thread during startup.

Method

ConfigureServicesForAppType

void ConfigureServicesForAppType(StartupContext context, IServiceCollection services) Source

Registers services required for the specific application type (for example, web or worker) into the provided service collection.

Parameters

  • contextStartup context containing application metadata, dependencies, and configuration used during registration.
  • servicesThe service collection to which app-type-specific services should be added or overridden.
Method

ConfigureBuilderForAppType

IHostBuilder ConfigureBuilderForAppType(StartupContext context, IHostBuilder builder) Source

Allows the startup to customize the host builder for the specific application type.

Parameters

  • contextThe startup context containing application metadata and dependency modules.
  • builderThe host builder to customize.

Returns

The configured IHostBuilder (by default returns the provided builder unchanged).

Type

IAppSurfaceHostModule

Source

Defines a module that can specifically configure the IHostBuilder before and after service registration. Only the root module of an application (or explicitly marked host modules) usually implements this.

Method

ConfigureHostBeforeServices

void ConfigureHostBeforeServices(StartupContext context, IHostBuilder builder) Source

Configures the IHostBuilder before any modules have their services configured.

Parameters

  • contextThe context for the current startup process.
  • builderThe host builder to configure.
Method

ConfigureHostAfterServices

void ConfigureHostAfterServices(StartupContext context, IHostBuilder builder) Source

Configures the IHostBuilder after all modules have their services configured.

Parameters

  • contextThe context for the current startup process.
  • builderThe host builder to configure.
Type

IAppSurfaceModule

Source

Defines a module that can configure services and register dependencies within the AppSurface host.

Remarks

Implement IAppSurfaceModule for reusable service-registration units that are not responsible for host lifecycle hooks. Create host-specific abstractions, or implement IAppSurfaceHostModule, when a module must configure hosting, middleware, endpoints, or other lifecycle behavior. Module methods run during startup; keep them idempotent, avoid heavy side effects and global state mutation, and throw clear configuration exceptions when required dependencies are missing.

Method

ConfigureServices

void ConfigureServices(StartupContext context, IServiceCollection services) Source

Configures the services for this module.

Parameters

  • contextThe context for the current startup process.
  • servicesThe service collection to add registrations to.

Remarks

ConfigureServices should add deterministic registrations to services and should tolerate being called during host construction before the application is running. Do not resolve runtime services or perform blocking I/O here unless the module explicitly documents that startup cost.

Method

RegisterDependentModules

void RegisterDependentModules(ModuleDependencyBuilder builder) Source

Registers other modules that this module depends on.

Parameters

  • builderThe builder used to declare module dependencies.

Remarks

Dependencies should be declared before their services are required. ModuleDependencyBuilder handles duplicate module types and pre-registers modules to avoid recursive cycles, but modules should still avoid relying on incidental traversal order for behavior.

Type

CommandResult

Source

Represents the captured result of a completed process execution.

Parameters

  • ExitCodeThe exit code returned by the process. A non-zero value indicates command failure, but it is still returned normally to the caller rather than being promoted to an exception.
  • StdoutThe exact text captured from standard output. This contains only the stdout stream and may be empty even when the process wrote diagnostics to standard error.
  • StderrThe exact text captured from standard error. This contains only the stderr stream and may be empty even when the process produced standard output.

Remarks

Stdout and Stderr are captured independently per stream. They are not a merged chronological timeline, so callers that care about exact interleaving between standard output and standard error must preserve that ordering separately.

ExitCode reflects the process exit value and may be non-zero without an exception being thrown. Startup failures and cancellation are surfaced as exceptions instead of a CommandResult.

Type

ProcessUtils

Source

Provides utility methods for executing external processes.

Method

ExecuteProcessAsync

2 overloads
Task<CommandResult> ExecuteProcessAsync(string fileName, IReadOnlyList<string> args, string workingDirectory, ILogger logger, CancellationToken cancellationToken, bool streamOutput = false, Func<string, LogLevel>? stderrLogLevelSelector = null) Source

Executes a process asynchronously and captures its output.

Parameters

  • fileNameThe path to the executable file to launch.
  • argsThe ordered list of command-line arguments to pass to the process.
  • workingDirectoryThe working directory used when starting the process.
  • loggerThe logger that receives streamed output when streamOutput is true.
  • cancellationTokenA token to monitor for cancellation requests.
  • streamOutputIf true, standard output and standard error are logged in real time and also captured in the returned CommandResult.
  • stderrLogLevelSelectorOptional selector that can remap the log level used for each standard error line when streamOutput is enabled. When omitted, standard error lines are logged at LogLevel.Error.

Returns

A CommandResult containing the process exit code and captured standard output/error. Non-zero exit codes are returned to the caller and are not treated as exceptions.

Exceptions

  • OperationCanceledExceptionThrown when cancellationToken is canceled.
  • InvalidOperationExceptionThrown if the process fails to start.

Remarks

When streamOutput is enabled, output is drained concurrently from both pipes, logged as lines arrive, and still buffered into the returned CommandResult. Any exception thrown by the logger or stderrLogLevelSelector is allowed to propagate so callers do not receive a partial success result with truncated output. The returned CommandResult preserves the exact standard output and standard error characters emitted by the process in both streaming and non-streaming modes.

Task<CommandResult> ExecuteProcessAsync(string fileName, IReadOnlyList<string> args, string workingDirectory, ILogger logger, CancellationToken cancellationToken, bool streamOutput, Func<string, LogLevel>? stderrLogLevelSelector, ProcessExecutionHooks? hooks) Source

Executes a process asynchronously with optional lifecycle hooks for deterministic testing.

Parameters

  • fileNameThe path to the executable file to launch.
  • argsThe ordered list of command-line arguments to pass to the process.
  • workingDirectoryThe working directory used when starting the process.
  • loggerThe logger that receives streamed output when streamOutput is enabled.
  • cancellationTokenA token to monitor for cancellation requests.
  • streamOutputIf true, standard output and standard error are logged in real time and also captured in the returned CommandResult.
  • stderrLogLevelSelectorOptional selector that can remap the log level used for each standard error line when streamOutput is enabled.
  • hooksOptional lifecycle hooks used by tests to simulate rare process runtime behaviors that are otherwise difficult to reproduce deterministically.

Returns

A CommandResult containing the process exit code and captured standard output/error.

Method

StreamToLoggerAsync

Task<string> StreamToLoggerAsync(TextReader reader, ILogger logger, LogLevel level, string fileName, CancellationToken cancellationToken, Func<string, LogLevel>? levelSelector = null) Source

Drains a text reader into a captured string while logging completed lines as they arrive.

Parameters

  • readerThe reader to drain.
  • loggerThe logger that receives completed output lines.
  • levelThe default log level used for each completed line.
  • fileNameThe process name included in structured log messages.
  • cancellationTokenThe token used to cancel the drain operation.
  • levelSelectorOptional selector that can remap the log level used for each completed line.

Returns

The exact text captured from reader, including original line terminators.

Exceptions

  • OperationCanceledExceptionThrown when cancellationToken is canceled before the reader is fully drained. Any unterminated trailing line is intentionally not logged in that case.

Remarks

This method is internal so tests can deterministically verify the stream-drain and cancellation behavior without depending on timing-sensitive child-process races.

Method

GetResultAsync

Task<string> GetResultAsync(Task<string>? task) Source

Gets the result of a task if it is a Task<string>.

Parameters

  • taskThe task to observe.

Returns

The string result if available, otherwise an empty string.

Method

ObserveTaskAsync

Task ObserveTaskAsync(Task<string>? task, string streamName, string fileName, ILogger logger) Source

Observes a task during cleanup and logs any exceptions without surfacing them.

Parameters

  • taskThe task to observe.
  • streamNameThe name of the stream (e.g., "stdout").
  • fileNameThe file name of the process being executed.
  • loggerThe logger for debugging.
Type

ProcessExecutionHooks

Source

Test hooks that allow deterministic verification of process lifecycle edge cases.

Remarks

Use these hooks only from tests that need to simulate rare runtime conditions such as Process.Start() returning false or process termination throwing during cleanup. Production code should continue to use the public ExecuteProcessAsync(string, IReadOnlyList{string}, string, ILogger, CancellationToken, bool, Func{string, LogLevel}?) overload, which executes real process operations without overrides.

Property

StartProcessOverride

Func<Process, bool>? StartProcessOverride { get; init; } Source

Gets or sets an optional process-start override.

Property

HasExitedOverride

Func<Process, bool>? HasExitedOverride { get; init; } Source

Gets or sets an optional process-state override for Process.HasExited.

Property

KillProcessOverride

Action<Process>? KillProcessOverride { get; init; } Source

Gets or sets an optional process-kill override used during cleanup.

Type

CriticalService

Source

A base class for background services that are critical to the application's operation. If a critical service fails or exits, the entire application will be shut down.

Method

RunAsync

Task RunAsync(CancellationToken stoppingToken) Source

Implements the core logic of the critical service.

Parameters

  • stoppingTokenA token that is signaled when the service should stop.

Returns

A task that represents the service's execution.

Method

LogInitialize

void LogInitialize(string serviceType) Source

Logs that the critical service is initializing.

Parameters

  • serviceTypeThe name of the service type.
Method

LogStopping

void LogStopping(string serviceType) Source

Logs that the critical service is stopping.

Parameters

  • serviceTypeThe name of the service type.
Method

LogException

void LogException(Exception exception, string serviceType) Source

Logs an unhandled exception that occurred in the critical service.

Parameters

  • exceptionThe unhandled exception.
  • serviceTypeThe name of the service type.