Skip to main content
The DistributedApplication class and IDistributedApplicationBuilder interface are the foundation of the .NET Aspire application model. They provide the entry point for defining distributed applications and orchestrating resources.

DistributedApplication

Represents a distributed application that implements IHost and IAsyncDisposable. This is the main entry point for running .NET Aspire applications.
public class DistributedApplication : IHost, IAsyncDisposable

Creating a Distributed Application

Use the static factory methods to create an application builder:
var builder = DistributedApplication.CreateBuilder(args);

var postgres = builder.AddPostgres("mypostgres");
var db = postgres.AddDatabase("inventory");

builder.AddProject<Projects.InventoryService>()
       .WithReference(db);

builder.Build().Run();

Static Methods

CreateBuilder()
IDistributedApplicationBuilder
Creates a new builder instance with no arguments. Use this only when not deploying with tools.
CreateBuilder(string[] args)
IDistributedApplicationBuilder
Creates a builder with command-line arguments. This is the recommended approach as it enables deployment tool support.Parameters:
  • args - Command-line arguments passed to the application
CreateBuilder(DistributedApplicationOptions)
IDistributedApplicationBuilder
Creates a builder with full configuration options.Parameters:
  • options - Configuration options including:
    • Args - Command-line arguments
    • DisableDashboard - Disable the Aspire dashboard
    • AllowUnsecuredTransport - Allow unsecured communication
    • ContainerRegistryOverride - Override the container registry
    • DashboardApplicationName - Custom application name for the dashboard

Instance Properties

Services
IServiceProvider
Gets the service provider configured for the application. Use this to resolve services after the application is built.
ResourceNotifications
ResourceNotificationService
Gets the service for monitoring and responding to resource state changes. Useful for:
  • Database seeding
  • Integration test readiness checks
  • Monitoring resource health
ResourceCommands
ResourceCommandService
Gets the service for executing resource commands programmatically or in tests.

Methods

Run()
void
Runs the application and blocks until shutdown is triggered (Ctrl-C, debugger detach, or dashboard browser close).
RunAsync(CancellationToken)
Task
Runs the application asynchronously and returns a task that completes when shutdown is triggered.Parameters:
  • cancellationToken - Optional cancellation token
StartAsync(CancellationToken)
Task
Starts the application without blocking. Returns a task that completes when startup is finished.
StopAsync(CancellationToken)
Task
Stops the application gracefully.

Resource Monitoring Example

Wait for Resource Health
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres").AddDatabase("mydb");
var app = builder.Build();

// Start the application
await app.StartAsync();

// Wait for the database to be healthy
await app.ResourceNotifications.WaitForResourceHealthyAsync("postgres");

// Seed the database
using var scope = app.Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<MyDbContext>();
await dbContext.Database.EnsureCreatedAsync();

// Continue running
await app.RunAsync();

IDistributedApplicationBuilder

The builder interface for configuring a distributed application before it is built.
public interface IDistributedApplicationBuilder

Properties

Environment
IHostEnvironment
Gets the hosting environment information (Development, Production, etc.).
Configuration
ConfigurationManager
Gets the configuration manager for accessing application configuration.
Services
IServiceCollection
Gets the service collection for registering dependency injection services.
Resources
IResourceCollection
Gets the collection of resources defined in the application.
Eventing
IDistributedApplicationEventing
Gets the eventing system for subscribing to application lifecycle events.
ExecutionContext
DistributedApplicationExecutionContext
Gets the execution context indicating whether the app is in Run, Publish, or Inspect mode.
AppHostDirectory
string
Gets the directory path of the app host project.

Methods

AddResource<T>(T)
IResourceBuilder<T>
Adds a resource to the application and returns a builder for further configuration.Parameters:
  • resource - The resource instance to add
Returns: A resource builder for chaining configuration methodsThrows: DistributedApplicationException if a resource with the same name already exists
CreateResourceBuilder<T>(T)
IResourceBuilder<T>
Creates a resource builder for an existing resource without adding it to the application.Parameters:
  • resource - The resource instance
Returns: A resource builder for configuration
Build()
DistributedApplication
Builds the configured application and returns a DistributedApplication instance ready to run.

Configuration Example

Service Registration
var builder = DistributedApplication.CreateBuilder(args);

// Add custom services
builder.Services.AddSingleton<IMyService, MyService>();

// Subscribe to events
builder.Eventing.Subscribe<BeforeStartEvent>(async (e, ct) => 
{
    Console.WriteLine("Application starting...");
});

// Check execution mode
if (builder.ExecutionContext.IsPublishMode)
{
    Console.WriteLine("Generating manifest for deployment");
}

var app = builder.Build();
await app.RunAsync();

Execution Modes

Aspire applications run in different modes depending on how they’re launched:
The normal mode when running the application locally. The app host orchestrates all resources and runs until shutdown.
if (builder.ExecutionContext.IsRunMode)
{
    // Add development-only resources
}
Activated when generating manifests for deployment tools. The app runs briefly to generate configuration.
if (builder.ExecutionContext.IsPublishMode)
{
    // Configure for production deployment
}
Used by tooling to inspect the application model without running resources.

Best Practices

Pass Command-Line Args

Always pass args to CreateBuilder() to enable deployment tool support and proper configuration.

Dispose Properly in Tests

Call DisposeAsync() on the application in test scenarios to clean up file watchers and resources.

Use Resource Notifications

Monitor resource health before performing operations like database seeding or integration tests.

Configure Services Early

Register custom services in builder.Services before calling Build().

Build docs developers (and LLMs) love