.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 orchestrator project, but they're designed to work best with the .NET Aspire app host.

Available components

The following table lists the .NET Aspire components currently available for use:

Component NuGet Description
Apache Kafka Aspire.Confluent.Kafka A library for producing and consuming messages from an Apache Kafka broker.
Azure AI OpenAI Aspire.Azure.AI.OpenAI A library for accessing Azure AI OpenAI or OpenAI functionality.
Azure Blob Storage Aspire.Azure.Storage.Blobs A library for accessing Azure Blob Storage.
Azure Cosmos DB Entity Framework Core Aspire.Microsoft.EntityFrameworkCore.Cosmos A library for accessing Azure Cosmos DB databases with Entity Framework Core.
Azure Cosmos DB Aspire.Microsoft.Azure.Cosmos A library for accessing Azure Cosmos DB databases.
Azure Key Vault Aspire.Azure.Security.KeyVault A library for accessing Azure Key Vault.
Azure Service Bus Aspire.Azure.Messaging.ServiceBus A library for accessing Azure Service Bus.
Azure Storage Queues Aspire.Azure.Storage.Queues A library for accessing Azure Storage Queues.
Azure Table Storage Aspire.Azure.Data.Tables A library for accessing the Azure Table service.
MongoDB Driver Aspire.MongoDB.Driver A library for accessing MongoDB databases.
MySqlConnector Aspire.MySqlConnector A library for accessing MySqlConnector databases.
Pomelo MySQL Entity Framework Core Aspire.Pomelo.EntityFrameworkCore.MySql A library for accessing MySql databases with Entity Framework Core.
Oracle Entity Framework Core Aspire.Oracle.EntityFrameworkCore A library for accessing Oracle databases with Entity Framework Core.
PostgreSQL Entity Framework Core Aspire.Npgsql.EntityFrameworkCore.PostgreSQL A library for accessing PostgreSQL databases using Entity Framework Core.
PostgreSQL Aspire.Npgsql A library for accessing PostgreSQL databases.
RabbitMQ Aspire.RabbitMQ.Client A library for accessing RabbitMQ.
Redis Distributed Caching Aspire.StackExchange.Redis.DistributedCaching A library for accessing Redis caches for distributed caching.
Redis Output Caching Aspire.StackExchange.Redis.OutputCaching A library for accessing Redis caches for output caching.
Redis Aspire.StackExchange.Redis A library for accessing Redis caches.
SQL Server Entity Framework Core Aspire.Microsoft.EntityFrameworkCore.SqlServer A library for accessing SQL Server databases using Entity Framework Core.
SQL Server Aspire.Microsoft.Data.SqlClient A library for accessing SQL Server databases.

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 Application 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:

  1. In the component consuming (worker service) project, install the Aspire.Npgsql NuGet package.

    dotnet add package Aspire.Npgsql --prerelease
    

    For more information, see dotnet add package or Manage package dependencies in .NET applications.

  2. 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.

  3. 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" Version="8.0.0-preview.3.24105.21" />
      </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.

  4. 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:
  5. Inject the NpgsqlDataSource object into the Worker 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": {
      "HealthChecks": false,
      "Tracing": false
    }
  }
}

Alternatively, you can configure the component directly in your code using a delegate:

builder.AddNpgsqlDataSource(
    "PostgreSqlConnection",
    static settings => settings.HealthChecks = false);

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.HealthChecks = false);

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 apps. 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 apps. 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.