Introduction
In the previous lessons, we separated the Catalog, Order, and Inventory services into independent APIs and data layers. That separation makes each service easier to develop and evolve, but it also introduces a practical development problem: starting several APIs and databases, managing connection information, and coordinating startup order manually becomes repetitive and error-prone.
In this lesson, we will move that operational knowledge into an Aspire AppHost. The AppHost is not another business service. It is a code-based application model that describes services, databases, containers, endpoints, and dependencies. Aspire uses this model to start resources during local development, inject connection information into consuming applications, and expose the running topology through the Aspire Dashboard. The AppHost acts as a central blueprint for how the resources in a distributed application fit together. ([learn.microsoft.com](https://learn.microsoft.com/en-us/dotnet/aspire/fundamentals/app-host-overview?utm_source=openai))
The application model and resources
In Aspire, each runnable component can be represented as a resource. An ASP.NET Core project, a SQL Server instance, a SQL Server database, a Redis container, or a RabbitMQ container can all be resources. Resource names provide logical identities inside the application model and are more useful than hardcoded localhost ports for describing relationships.
For our solution, the initial model can look like this:
| Resource | Purpose |
|---|---|
catalog-api | Provides product and category operations |
order-api | Manages order operations |
inventory-api | Manages stock information |
sql | Represents the SQL Server container |
catalogdb, orderdb, inventorydb | Databases owned by individual services |
The important architectural decision is that each service owns its own database. The AppHost does not remove that ownership boundary; it only describes how the resources are started and connected during development.
Step 1: Create the AppHost project
From the root of an existing .NET solution, you can use the Aspire CLI to initialize an AppHost. The aspire init command is useful when you want to add Aspire to an existing solution rather than generate a completely new one. It analyzes the solution and creates a project-based AppHost. ([learn.microsoft.com](https://learn.microsoft.com/en-us/dotnet/aspire/get-started/add-aspire-existing-app?utm_source=openai))
cd DistributedShop
aspire initAlternatively, create an AppHost project and add references to the service projects explicitly:
dotnet new aspire-apphost -n DistributedShop.AppHost
dotnet sln add DistributedShop.AppHost/DistributedShop.AppHost.csproj
dotnet add DistributedShop.AppHost reference src/Catalog/Catalog.Api.csproj
dotnet add DistributedShop.AppHost reference src/Order/Order.Api.csproj
dotnet add DistributedShop.AppHost reference src/Inventory/Inventory.Api.csprojWhen the AppHost references the service projects, Aspire generates strongly typed project metadata under the Projects namespace. This allows AddProject calls to use compile-time project information instead of manually written project paths. You also gain IntelliSense and build-time validation. ([learn.microsoft.com](https://learn.microsoft.com/en-us/dotnet/aspire/get-started/add-aspire-existing-app?utm_source=openai))
Step 2: Add the SQL Server hosting integration
The AppHost can run SQL Server as a container during local development. Add the SQL Server hosting integration to the AppHost project:
cd DistributedShop.AppHost
aspire add sqlserverThe integration provides APIs for declaring a SQL Server instance and one or more databases in the application model. When an application references a database resource, Aspire can provide the connection information through environment-backed configuration. ([learn.microsoft.com](https://learn.microsoft.com/en-us/dotnet/aspire/database/sql-server-integrations?WT.mc_id=api_CatalogApi&utm_source=openai))
Step 3: Define the AppHost model
Update the AppHost’s Program.cs file. Replace the generated project type names with the actual project names from your solution.
var builder = DistributedApplication.CreateBuilder(args);
var sql = builder.AddSqlServer("sql")
.WithDataVolume();
var catalogDb = sql.AddDatabase("catalogdb");
var orderDb = sql.AddDatabase("orderdb");
var inventoryDb = sql.AddDatabase("inventorydb");
var catalogApi = builder
.AddProject<Projects.DistributedShop_Catalog_Api>("catalog-api")
.WithReference(catalogDb)
.WaitFor(sql)
.WithHttpHealthCheck("/health");
var orderApi = builder
.AddProject<Projects.DistributedShop_Order_Api>("order-api")
.WithReference(orderDb)
.WaitFor(sql)
.WithHttpHealthCheck("/health");
var inventoryApi = builder
.AddProject<Projects.DistributedShop_Inventory_Api>("inventory-api")
.WithReference(inventoryDb)
.WaitFor(sql)
.WithHttpHealthCheck("/health");
builder.Build().Run();DistributedApplication.CreateBuilder creates the application model builder. AddSqlServer("sql") declares the SQL Server resource. Each AddDatabase call creates a logical database resource inside that SQL Server instance. Every API references only the database it owns through WithReference.
WaitFor(sql) expresses a startup dependency so the APIs do not begin before the SQL Server resource is ready. WithHttpHealthCheck tells Aspire how to monitor the service. The corresponding health endpoint must actually exist in the API; otherwise, the resource may appear unhealthy.
Step 4: Consume the connection in an API
The AppHost provides the connection information, but the API must read the expected configuration key. In the Catalog API, the connection can be consumed as ConnectionStrings:catalogdb:
var builder = WebApplication.CreateBuilder(args);
var connectionString =
builder.Configuration.GetConnectionString("catalogdb")
?? throw new InvalidOperationException(
"The catalogdb connection string was not provided.");
builder.Services.AddDbContext<CatalogDbContext>(options =>
options.UseSqlServer(connectionString));
builder.AddServiceDefaults();
var app = builder.Build();
app.MapDefaultEndpoints();
app.MapControllers();
app.Run();The API does not hardcode a SQL Server host, password, port, or container address. Those values are supplied by the hosting model for the current environment. Local development may use a container endpoint, while another environment may provide a platform-managed database endpoint. The application code remains environment-independent.
The resource name and the configuration key must remain consistent. If the AppHost declares catalogdb but the API reads DefaultConnection, the application may fail during startup because the expected value is missing.
Step 5: Preserve database ownership
Declaring three databases inside one SQL Server instance does not mean that all services should share tables. The Catalog API should access catalogdb, the Order API should access orderdb, and the Inventory API should access inventorydb.
This design provides several benefits:
- A schema change in one service is less likely to break another service’s tables.
- EF Core migrations remain inside the owning service boundary.
- Services can later move to different SQL Server instances.
- Cross-service data access is encouraged through API contracts or messages instead of direct table access.
Using one SQL Server container during local development can be convenient. In production, however, each database might require a separate server, security policy, backup strategy, or scaling profile. Modeling the resources explicitly in the AppHost makes those boundaries visible early.
Step 6: Run the system with the Aspire Dashboard
From the directory that contains the AppHost, run:
aspire runThe Aspire CLI discovers the AppHost, builds the project and its resources, starts the application model, and prints the Dashboard address. The Dashboard provides a single view of resource state, endpoints, logs, health information, and telemetry. ([learn.microsoft.com](https://learn.microsoft.com/en-us/dotnet/aspire/get-started/build-your-first-aspire-app?utm_source=openai))
Use the Dashboard to verify the following:
- The
sqlresource reaches a Running state. - The
catalogdb,orderdb, andinventorydbresources are present. - All three API endpoints are listed.
- The dependency relationships between the APIs and SQL Server are visible.
- The health endpoints report successful results.
- A request to an API produces logs and, when telemetry is configured, trace data.
When started from the command line, the Dashboard displays a local login address containing a token. Token authentication is important because the Dashboard can expose environment variables, connection details, and other sensitive diagnostic information. ([learn.microsoft.com](https://learn.microsoft.com/en-us/dotnet/aspire/fundamentals/dashboard/explore?utm_source=openai))
Common mistakes
1. Missing project references
If a type such as Projects.SomeProject cannot be resolved, the AppHost may not reference the corresponding API project. Add the project reference and rebuild the solution.
2. Using the wrong connection string name
If the AppHost declares a database resource named catalogdb but the API reads DefaultConnection, the connection may not be found. Keep the resource name and configuration key aligned.
3. Confusing WithReference and WaitFor
WithReference establishes a resource relationship and provides configuration or service discovery information. WaitFor expresses startup ordering. They solve different problems and are often used together.
4. Sharing one database across services
Referencing the Catalog database from the Order API may appear convenient, but it weakens data ownership. Use an API contract or messaging when the Order service needs information owned by Catalog.
5. Losing local data
A container can be recreated during development. Without persistent storage, database data may disappear. Using WithDataVolume() helps separate local data from the lifecycle of the SQL Server container.
Practice exercise
Extend the AppHost as follows:
- Verify that the Catalog API reads from
catalogdb. - Connect the Inventory API to
inventorydb. - Ensure that both APIs expose a successful
/healthendpoint. - Start the system with
aspire run. - Inspect one API request in the Dashboard and review its logs, endpoint, and resource relationships.
For an additional design task, model how the Order API could depend on the Catalog API without accessing the Catalog database directly. Do not implement the client yet; simply identify the resource relationship that should exist in the AppHost and explain why it is needed.
Conclusion
In this lesson, we created the first application model for our microservice solution with an Aspire AppHost. We registered the API projects as resources, modeled SQL Server and three service-owned databases, connected each service only to its own database, and ran the complete system through the Aspire Dashboard.
The main value of this approach is that infrastructure and orchestration knowledge stays in one explicit, version-controlled AppHost instead of being scattered across service code and local scripts. In the next lessons, we will extend this model with Redis, RabbitMQ, service-to-service communication, resilience, and deeper observability.
Sources
- https://learn.microsoft.com/en-us/dotnet/aspire/fundamentals/app-host-overview
- https://learn.microsoft.com/en-us/dotnet/aspire/get-started/add-aspire-existing-app
- https://learn.microsoft.com/en-us/dotnet/aspire/database/sql-server-integrations
- https://learn.microsoft.com/en-us/dotnet/aspire/get-started/build-your-first-aspire-app
- https://learn.microsoft.com/en-us/dotnet/aspire/cli/overview
- https://learn.microsoft.com/en-us/dotnet/aspire/fundamentals/dashboard/explore