Skip to main content

.NET Aspire

Respire.Aspire registers Respire clients from Aspire connection strings, with health checks, OpenTelemetry, and logging. Use it in a .NET 10 or .NET 11 service that an AppHost starts with a Redis, Valkey, or Azure Managed Redis reference. For a runnable AppHost, see the .NET Aspire sample.

Install​

dotnet add package Respire.Aspire

Register a client​

Register clients on any IHostApplicationBuilder:

using Microsoft.Extensions.Hosting;
using Respire;

builder.AddRespireClient("cache");
builder.AddKeyedRespireClient("valkey");
  • The default singleton exposes IRespireClient and RespireClient.
  • A keyed client uses the connection name as its key: inject [FromKeyedServices("valkey")] IRespireClient.
  • A second default registration or a duplicate key throws.
  • The host owns and disposes the clients. They connect in the background when the host starts; host startup does not wait for Redis. See connect at startup.

Hosting resources​

In the AppHost, use the normal Aspire hosting integrations and references:

var cache = builder.AddRedis("cache");
var valkey = builder.AddValkey("valkey");
builder.AddDotnetProject("api", "../Api/Api.csproj")
.WithReference(cache).WaitFor(cache)
.WithReference(valkey).WaitFor(valkey);

The hosting integrations (Redis, Valkey, and Azure Managed Redis) inject ConnectionStrings__cache and ConnectionStrings__valkey, so the service needs no host, port, or password settings. Respire reads TLS, username, password, and database from the string.

AddDotnetProject registers the service by project path, so the AppHost references the Aspire.Hosting.Dotnet package instead of the service project. Building the AppHost project does not build the service; Aspire builds it when the AppHost starts, before launching it.

Configuration​

Settings live under Aspire:Respire, with per-client overrides under Aspire:Respire:<connectionName>. They apply in this order:

  1. Global integration settings.
  2. Named integration settings.
  3. ConnectionStrings:<connectionName>.
  4. The configureSettings callback.
  5. Parse the resulting connection string into RespireOptions.
  6. Apply global Aspire:Respire:Options, then named Aspire:Respire:<connectionName>:Options.
  7. Run configureOptions when creating the singleton client.

If client creation fails and you resolve the client again, the callback receives fresh options. By default those options come from the configuration read at registration.

Aspire validates the topology after applying these settings. To use a connection string such as seed-a:6379,seed-b:6380, set UseCluster to true in the global or named Options section.

{
"Aspire": {
"Respire": {
"Options": { "CommandTimeout": "00:00:05", "Connections": 1 },
"cache": {
"DisableTracing": false,
"Options": { "ClientName": "web", "ReconnectPolicy": { "MaxAttempts": 4 } }
}
}
}
}

Integration settings​

SettingDefaultEffect
ConnectionStringnullUsed when ConnectionStrings:<connectionName> is absent.
DisableHealthChecksfalseSkips the health check registration.
DisableTracingfalseSkips adding the Respire activity source.
DisableMetricsfalseSkips adding the Respire meter.
DisableLoggingfalseGives the client a null logger factory.
DeferConfigurationfalseReads the connection string and Options sections when the client is first resolved.

Deferred configuration​

By default the connection string and Options sections are read when you call AddRespireClient. A test host that adds its own Redis endpoint after the application registers its services would still get the original endpoint. Set DeferConfiguration to read them when the client is first resolved instead:

builder.AddRespireClient("cache", settings => settings.DeferConfiguration = true);

The precedence above still applies. A connection string assigned in configureSettings still wins, even when it matches the configured value or is null. The other integration settings, including DeferConfiguration itself, are read at registration. A missing endpoint or an invalid value is reported when the client is first resolved, not at registration.

Options section​

Options binds scalar RespireOptions fields, endpoints, replica endpoints, the node address map, hedged reads, and the ReconnectPolicy, RetryPolicy, CircuitBreaker, DedicatedPool and ClientSideCache sections. It also binds the scalar settings in TlsOptions and SentinelTlsOptions.

  • Endpoint arrays accept strings such as "localhost:6379" or objects such as { "Host": "localhost", "Port": 6379 }.
  • A named array replaces the global one; an absent one inherits it. An empty array ([]) clears the global endpoints, replica endpoints, or client-cache prefixes.
  • Use JSON arrays for these settings. A nonempty scalar value throws an error naming the configuration path.
  • If you clear all primary endpoints, an options callback must supply them.
  • Set "ClientSideCache": null in the named client's Options to disable a globally configured client-side cache. Omit ClientSideCache to inherit it, or specify individual cache settings to override them. The .NET JSON configuration provider represents an empty object ({}) the same way as null. Both disable the cache when the named section has no cache fields from other configuration providers.
  • Client-side cache key prefixes are strings. KeyPrefix takes a text prefix; see default key namespaces.
  • Time spans use the invariant .NET format. An empty string clears a nullable value: "CommandTimeout": "" removes the command timeout.
  • An invalid value throws InvalidOperationException naming the configuration path.

The builder's Settings property is a read-only snapshot; changing it does not affect the client.

Options callback​

Set services, serializers, binary key prefixes, certificates, and TLS callbacks in code. The callback receives the parsed and bound options and can resolve services:

builder.AddRespireClient("cache", configureOptions: (services, options) => options with
{
ClientName = "web",
CredentialProvider = services.GetRequiredService<IRespireCredentialProvider>(),
});

A callback can supply endpoints when there is no connection string. Missing endpoints throw InvalidOperationException: at registration without a callback, or when the client is resolved with one (as does a null result).

Health checks, logging, and OpenTelemetry​

All four are on by default. Turn one off globally, per connection, or in configureSettings:

builder.AddRespireClient("cache", settings => settings.DisableTracing = true);

Health checks​

Checks are named respire_default_<connectionName> or respire_keyed_<connectionName>, with the ready tag. A check reuses existing connections and opens none. The client connects in the background when the host starts, so the check turns healthy without application traffic. See health checks.

Tracing and metrics​

The integration adds the Respire activity source and meter to the host's OpenTelemetry providers. Configure exporters yourself, for example builder.Services.AddOpenTelemetry().UseOtlpExporter() for the Aspire dashboard.

To export command duration, call RespireMetrics.Configure(new RespireMetricsOptions { Groups = RespireMetricGroups.Default | RespireMetricGroups.Command }) before you register providers or create clients. See observability.

Providers are per host, not per client: if any client enables a signal, every client's telemetry for it is observed. The flags only skip this integration's wiring; they do not suppress listeners registered elsewhere.

Logging​

Clients use the host's logger factory. DisableLogging gives the client a null logger factory, even if options supply another.

Cache companions​

Install the companion package for each cache API you need:

PackageRegistration on an existing client builder
Respire.Aspire.DistributedCaching.AddDistributedCache(...)
Respire.Aspire.HybridCaching.AddHybridCache(configureCache, configureHybrid)
Respire.Aspire.OutputCaching.AddOutputCache(...)
builder.AddRespireClientBuilder("cache")
.AddHybridCache(options => options.InstanceName = "app:cache:")
.AddOutputCache(options => options.InstanceName = "app:output:");

Use AddKeyedRespireClientBuilder for a keyed client. Companions reuse the host-owned client and never dispose it.

  • HybridCache uses the distributed cache as its L2. See Microsoft caching and output caching.
  • IDistributedCache, HybridCache, and IOutputCacheStore stay unkeyed, even with a keyed client. Choose one backend for each. If you register several, the last one wins, with its options and client.
  • The base Respire.Aspire package has no ASP.NET Core dependency.

Azure Managed Redis with Microsoft Entra​

Add Respire.Azure and an Azure credential package. Grant the identity Redis access. The provider derives the Redis username from the access token's oid claim, so deployment configuration does not need to supply the identity's object ID:

using global::Azure.Core;
using global::Azure.Identity;
using Respire.Azure;

builder.Services.AddSingleton<TokenCredential>(new DefaultAzureCredential());
builder.AddRespireClient("cache", configureOptions: (services, options) => options with
{
CredentialProvider = new RespireAzureManagedRedisCredentialProvider(
services.GetRequiredService<TokenCredential>()),
});

The hosting reference supplies the endpoint and TLS (a connection string such as host:10000,ssl=true, which Respire accepts). The provider refreshes Entra credentials; you own the credential. See Azure Managed Redis.