.NET Aspire components overview
.NET Aspire components are a curated suite of NuGet packages specifically selected to facilitate the integration of cloud-native applications with prominent services and platforms, including but not limited to Redis and PostgreSQL. Each component furnishes essential cloud-native functionalities through either automatic provisioning or standardized configuration patterns. .NET Aspire components can be used without an app host (orchestrator) project, but they're designed to work best with the .NET Aspire app host.
.NET Aspire components should not be confused with .NET Aspire hosting packages, as they serve different purposes. Hosting packages are used to model and configure various resources in a .NET Aspire project, while components are used to map configuration to various client libraries.
Tip
Always strive to use the latest version of .NET Aspire components to take advantage of the latest features, improvements, and security updates.
Available components
The following table lists the .NET Aspire components currently available for use:
For more information on working with .NET Aspire components in Visual Studio, see Visual Studio tooling.
Explore a sample component workflow
.NET Aspire components streamline the process of consuming popular services and platforms. For example, consider the .NET Aspire project template. With this template, you get the AppHost and ServiceDefaults projects. Imagine that you have a need for a worker service to perform some database processing. You could use the .NET Aspire PostgreSQL component to connect to and utilize a PostgreSQL database. The database could be hosted on-prem or in a cloud service such as Azure, AWS, or GCP. The following steps demonstrate how to integrate this component into your app:
In the component consuming (worker service) project, install the Aspire.Npgsql NuGet package.
dotnet add package Aspire.Npgsql
For more information, see dotnet add package or Manage package dependencies in .NET applications.
In the Program.cs file of your worker service project, call the AddNpgsqlDataSource extension method to register
NpgsqlDataSource
as a service.using WorkerService; var builder = Host.CreateApplicationBuilder(args); builder.AddNpgsqlDataSource("customers"); builder.AddServiceDefaults(); builder.Services.AddHostedService<Worker>(); var host = builder.Build(); host.Run();
The preceding code adds the
NpgsqlDataSource
to the dependency injection container with the connection name of"customers"
. The connection name is later used by the orchestrator project, when expressing resource dependencies.Tip
Components that are designed to connect to Azure services also support passwordless authentication and authorization using Azure RBAC, which is the recommended approach for production apps.
In your app host project (the project with the *.AppHost suffix), add a reference to the worker service project. If you're using Visual Studio, you can use the Add .NET Aspire Orchestrator Support project context menu item to add the reference automatically. The following code snippet shows the project reference of the AspireApp.AppHost.csproj:
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net8.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> <IsAspireHost>true</IsAspireHost> </PropertyGroup> <ItemGroup> <PackageReference Include="Aspire.Hosting.AppHost" Version="8.0.1" /> <PackageReference Include="Aspire.Hosting.PostgreSQL" Version="8.0.1" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\WorkerService\WorkerService.csproj" /> </ItemGroup> </Project>
After the worker service is referenced by the orchestrator project, the worker service project has its Program.cs file updated to call the
AddServiceDefaults
method. For more information on service defaults, see Service defaults.In the orchestrator project, update the Program.cs file with the following code:
var builder = DistributedApplication.CreateBuilder(args); var database = builder.AddPostgres("postgresql") .AddDatabase("customers"); builder.AddProject<Projects.WorkerService>("workerservice") .WithReference(database) .WithReplicas(3); builder.Build().Run();
The preceding code:
- Calls AddPostgres and chains a call to AddDatabase, adding a PostgreSQL database container to the app model with a database named
"customers"
. - Chains calls on the result of the AddProject from the worker service project:
- Calls WithReference to add a reference to the
database
. - Calls WithReplicas to set the number of replicas to
3
.
- Calls WithReference to add a reference to the
- Calls AddPostgres and chains a call to AddDatabase, adding a PostgreSQL database container to the app model with a database named
Inject the
NpgsqlDataSource
object into theWorker
to run commands against the database:using Npgsql; namespace WorkerService; public sealed class Worker( ILogger<Worker> logger, NpgsqlDataSource dataSource) : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { // Use the dataSource await Task.Delay(15_000, stoppingToken); } } }
You now have a fully configured PostgreSQL database component and corresponding container with connection integrated into your app! This component also configured health checks, logging, metrics, retries, and other useful capabilities for you behind the scenes. .NET Aspire components provide various options to configure each of these features.
Configure .NET Aspire components
.NET Aspire components implement a consistent configuration experiences via IConfiguration and IOptions<TOptions>. Configuration is schematized and part of a component's contract, ensuring backward compatibility across versions of the component. You can set up every .NET Aspire component through either JSON configuration files or directly through code using delegates. JSON files must follow a standardized naming convention based on the Component name.
For example, add the following code to the appsettings.json file to configure the PostgreSQL component:
{
"Aspire": {
"Npgsql": {
"DisableHealthChecks": true,
"DisableTracing": true
}
}
}
Alternatively, you can configure the component directly in your code using a delegate:
builder.AddNpgsqlDataSource(
"PostgreSqlConnection",
static settings => settings.DisableHealthChecks = true);
Dependency injection
.NET Aspire components automatically register essential services with the .NET dependency container using the proper scope. This allows key component classes and services to be injected throughout your code. For example, the .NET Aspire PostgreSQL component makes available the NpgsqlDataSource
to inject into your application layers and run commands against a database:
public class ExampleService(NpgsqlDataSource dataSource)
{
}
For more information, see .NET dependency injection.
Keyed services
.NET Aspire components also support keyed dependency injection. In this scenario, the service name for keyed dependency injection will be the same as the connection name:
builder.AddKeyedNpgsqlDataSource(
"PostgreSqlConnection",
static settings => settings.DisableHealthChecks = true);
You can then retrieve the registered service using the FromKeyedServicesAttribute:
public class ExampleService(
[FromKeyedServices("PostgreSqlConnection")] NpgsqlDataSource npgContext)
{
}
For more information, see Dependency injection in .NET: Keyed services.
Cloud-native features
Cloud-native applications surface many unique requirements and concerns. The core features of .NET Aspire orchestration and components are designed to handle many cloud-native concerns for you with minimal configurations. Some of the key features include:
- Orchestration: A lightweight, extensible, and cross-platform app host for .NET Aspire projects. The app host provides a consistent configuration and dependency injection experience for .NET Aspire components.
- Service discovery: A technique for locating services within a distributed application. Service discovery is a key component of microservice architectures.
- Service defaults: A set of default configurations intended for sharing amongst resources within .NET Aspire projects. These defaults are designed to work well in most scenarios and can be customized as needed.
Some .NET Aspire components also include more capabilities for specific services or platforms, which can be found in the component specific reference docs.
Observability and telemetry
.NET Aspire components automatically set up Logging, Tracing, and Metrics configurations, which are sometimes known as the pillars of observability.
Logging: A technique where code is instrumented to produce logs of interesting events that occurred while the program was running. A baseline set of log events are enabled for .NET Aspire components by default and more extensive logging can be enabled on-demand to diagnose particular problems.
Tracing: A specialized form of logging that helps you localize failures and performance issues within applications distributed across multiple machines or processes. This technique tracks requests through an application to correlate work done by different application components and separate it from other work the application may be doing for concurrent requests.
Metrics: Numerical measurements recorded over time to monitor application performance and health. Metrics are often used to generate alerts when potential problems are detected. Metrics have low performance overhead and many services configure them as always-on telemetry.
Together, these types of telemetry allow you to gain insights into your application's behavior and performance using various monitoring and analysis tools. Depending on the backing service, some components may only support some of these features. For example, some components support logging and tracing, but not metrics. Telemetry features can also be disabled. For more information, see .NET Aspire service defaults.
Health checks
.NET Aspire components enable health checks for services by default. Health checks are HTTP endpoints exposed by an app to provide basic availability and state information. These endpoints can be configured to report information used for various scenarios:
- Influence decisions made by container orchestrators, load balancers, API gateways, and other management services. For instance, if the health check for a containerized app fails, it might be skipped by a load balancer routing traffic.
- Verify that underlying dependencies are available, such as a database or cache, and return an appropriate status message.
- Trigger alerts or notifications when an app isn't responding as expected.
For example, the .NET Aspire PostgreSQL component automatically adds a health check at the /health
URL path to verify the following:
- A database connection could be established
- A database query could be executed successfully
If either of these operations fail, the health check also fails. For more information, see Health checks in .NET Aspire.
Resiliency
.NET Aspire components enable resiliency configurations automatically where appropriate. Resiliency is the ability of your system to react to failure and still remain functional. Resiliency extends beyond preventing failures to include recovering and reconstructing your cloud-native environment back to a healthy state. Examples of resiliency configurations include:
Connection retries: You can configure some .NET Aspire components to retry requests that initially fail. For example, failed database queries can be retried multiple times if the first request fails. This creates tolerance in environments where service dependencies may be briefly unresponsive or unavailable when the system state changes.
Timeouts: You can configure how long an .NET Aspire component waits for a request to finish before it times out. Timeout configurations can be useful for handling dependencies with variable response times.
For more information, see Build resilient HTTP apps.
.NET Aspire
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for