Connect to Garnet
This page describes how consuming apps connect to a Garnet resource that’s already modeled in your AppHost. For the AppHost API surface — adding a Garnet resource, data volumes, persistence, parameters, and more — see Garnet Hosting integration.
When you reference a Garnet resource from your AppHost, Aspire injects the connection information into the consuming app as environment variables. Your app can either read those environment variables directly — the pattern works the same from any language — or, in C#, use the Aspire Redis client integration (Garnet is RESP-compatible) for automatic dependency injection, health checks, and telemetry.
These connection properties are available when the AppHost models a typed Garnet resource (for example, AddGarnet("cache")) and references it from a consuming app. If the AppHost uses AddConnectionString("cache") or addConnectionString("cache"), consuming apps receive a single ConnectionStrings value (ConnectionStrings:cache / ConnectionStrings__cache) instead of deconstructed resource variables such as CACHE_URI, CACHE_HOST, and CACHE_PORT.
Connection properties
Section titled “Connection properties”Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called cache becomes CACHE_URI.
The Garnet resource exposes the following connection properties:
| Property Name | Description |
|---|---|
Host | The hostname or IP address of the Garnet server |
Port | The port number the Garnet server is listening on |
Password | The password for authentication |
Uri | The connection URI, with the format garnet://:{Password}@{Host}:{Port} |
Example connection string:
Uri: garnet://:p%40ssw0rd1@localhost:6379Environment variables and connection string formats
Section titled “Environment variables and connection string formats”The way Aspire exposes connection information depends on how the Garnet resource is modeled in your AppHost:
Using WithReference (typed Garnet resource)
Section titled “Using WithReference (typed Garnet resource)”When your AppHost adds a typed Garnet resource with builder.AddGarnet("cache") and references it with .WithReference(cache), Aspire injects individual connection properties as environment variables using the [RESOURCE]_[PROPERTY] format:
CACHE_HOST= hostnameCACHE_PORT= port numberCACHE_PASSWORD= password (if set)CACHE_URI= full connection URI
This is the recommended approach because Aspire manages the resource lifecycle, configuration, and provides typed client integrations.
Using AddConnectionString (external connection string)
Section titled “Using AddConnectionString (external connection string)”When your AppHost uses builder.AddConnectionString("cache") to reference an existing, pre-configured Garnet instance outside Aspire’s control, only a single connection string environment variable is injected:
ConnectionStrings__cache= the full connection string provided toAddConnectionString
With this approach, there are no individual property variables (CACHE_HOST, CACHE_PORT, etc.). Consuming apps must parse the connection string themselves or use client libraries that accept a connection string directly.
Connect from your app
Section titled “Connect from your app”Pick the language your consuming app is written in. Each example assumes your AppHost adds a Garnet resource named cache and references it from the consuming app.
For C# apps, the recommended approach is the Aspire Redis client integration — Garnet is RESP-compatible, so the same client works. It registers an IConnectionMultiplexer through dependency injection and adds health checks and telemetry automatically. If you’d rather read environment variables directly, see the Read environment variables section at the end of this tab.
Install the client integration
Section titled “Install the client integration”Install the 📦 Aspire.StackExchange.Redis NuGet package in the client-consuming project:
dotnet add package Aspire.StackExchange.Redis#:package Aspire.StackExchange.Redis@*<PackageReference Include="Aspire.StackExchange.Redis" Version="*" />Add the Redis client
Section titled “Add the Redis client”In Program.cs, call AddRedisClient on your IHostApplicationBuilder to register an IConnectionMultiplexer:
builder.AddRedisClient(connectionName: "cache");Resolve the connection multiplexer through dependency injection:
public class ExampleService(IConnectionMultiplexer connectionMux){ // Use connection multiplexer...}Add keyed Redis clients
Section titled “Add keyed Redis clients”To register multiple IConnectionMultiplexer instances with different connection names, use AddKeyedRedisClient:
builder.AddKeyedRedisClient(name: "chat");builder.AddKeyedRedisClient(name: "queue");Then resolve each instance by key:
public class ExampleService( [FromKeyedServices("chat")] IConnectionMultiplexer chatMux, [FromKeyedServices("queue")] IConnectionMultiplexer queueMux){ // Use connections...}Configuration
Section titled “Configuration”The Aspire Redis client integration offers multiple ways to provide configuration.
Connection strings. When using a connection string from the ConnectionStrings configuration section, pass the connection name to AddRedisClient:
builder.AddRedisClient("cache");The connection string is resolved from the ConnectionStrings section:
{ "ConnectionStrings": { "cache": "localhost:6379" }}For more information, see Stack Exchange Redis configuration.
Configuration providers. The client integration supports Microsoft.Extensions.Configuration. It loads StackExchangeRedisSettings from appsettings.json (or any other configuration source) by using the Aspire:StackExchange:Redis key:
{ "Aspire": { "StackExchange": { "Redis": { "ConnectionString": "localhost:6379", "DisableHealthChecks": false, "DisableTracing": false } } }}Inline delegates. Pass an Action<StackExchangeRedisSettings> to configure settings inline, for example to disable tracing:
builder.AddRedisClient( "cache", static settings => settings.DisableTracing = true);Client integration health checks
Section titled “Client integration health checks”Aspire client integrations enable health checks by default. The Redis client integration adds a health check that verifies the Garnet instance is reachable and can execute commands. The health check is wired into the /health HTTP endpoint, where all registered health checks must pass before the app is considered ready to accept traffic.
Observability and telemetry
Section titled “Observability and telemetry”The Aspire Redis client integration automatically configures logging, tracing, and metrics through OpenTelemetry.
Logging categories:
Aspire.StackExchange.Redis
Tracing activities:
OpenTelemetry.Instrumentation.StackExchangeRedis
Metrics are emitted through OpenTelemetry. Any of these telemetry features can be disabled through the configuration options above.
Distributed caching and output caching
Section titled “Distributed caching and output caching”Garnet also works with the Aspire distributed-caching and output-caching client integrations because they’re built on top of the same Redis client. Install the respective packages and follow their guides:
- Aspire.StackExchange.Redis.DistributedCaching — see Get started with Redis distributed caching.
- Aspire.StackExchange.Redis.OutputCaching — see Get started with Redis output caching.
Read environment variables in C#
Section titled “Read environment variables in C#”If you prefer not to use the Aspire client integration, you can read the Aspire-injected connection URI from the environment and pass it to 📦 StackExchange.Redis directly:
using StackExchange.Redis;
var connectionString = Environment.GetEnvironmentVariable("CACHE_URI");var mux = await ConnectionMultiplexer.ConnectAsync(connectionString!);
var db = mux.GetDatabase();// Use db to interact with Garnet...Use go-redis, the most actively maintained Go client for the RESP protocol:
go get github.com/redis/go-redis/v9Read the injected environment variable and connect:
package main
import ( "context" "os" "github.com/redis/go-redis/v9")
func main() { // Read the Aspire-injected connection URI opt, err := redis.ParseURL(os.Getenv("CACHE_URI")) if err != nil { panic(err) }
rdb := redis.NewClient(opt) defer rdb.Close()
_ = rdb.Ping(context.Background()).Err()}Install redis-py, the official Python client for RESP servers including Garnet:
pip install redisRead the injected environment variable and connect:
import osimport redis
# Read the Aspire-injected connection URIclient = redis.from_url(os.getenv("CACHE_URI"))
client.ping()# Use client to interact with Garnet...Install ioredis, the most popular RESP client for Node.js:
npm install ioredisRead the injected environment variables and connect:
import Redis from 'ioredis';
// Read Aspire-injected connection propertiesconst client = new Redis({ host: process.env.CACHE_HOST, port: Number(process.env.CACHE_PORT), password: process.env.CACHE_PASSWORD,});
await client.ping();Or use the connection URI directly:
import Redis from 'ioredis';
const client = new Redis(process.env.CACHE_URI!);