如何在ASP.NET Core默认容器中注册ServiceStack Redis Client Manager单例
Injecting
IRedisClientsManager via RedisManagerPool Without ServiceStack AppHost Got it, I totally get where you're coming from—you want to stick with your existing IOC container, avoid ServiceStack's AppHost and its built-in DI entirely, and only use their Redis client component. Here's a clean, straightforward way to make this work:
Step 1: Install the Minimal NuGet Package
First, grab only the core ServiceStack Redis package (no extra fluff required):
# For Package Manager Console Install-Package ServiceStack.Redis # For .NET CLI dotnet add package ServiceStack.Redis
Step 2: Register RedisManagerPool as a Singleton in ConfigureServices
You can directly register RedisManagerPool (which implements IRedisClientsManager) as a singleton in your setup—this keeps things isolated to just the Redis client, no AppHost or ServiceStack DI needed:
using ServiceStack.Redis; public void ConfigureServices(IServiceCollection services) { // Fetch your Redis connection string (adjust this to your environment) // For better practice, read this from appsettings.json instead of hardcoding var redisConnectionString = Configuration.GetConnectionString("Redis") ?? "localhost:6379"; // Register the RedisManagerPool as the singleton IRedisClientsManager implementation services.AddSingleton<IRedisClientsManager>(_ => new RedisManagerPool(redisConnectionString)); // Optional: If you want to inject a scoped IRedisClient directly (for per-request usage) services.AddScoped<IRedisClient>(sp => sp.GetRequiredService<IRedisClientsManager>().GetClient()); }
Why This Works
RedisManagerPoolis a standalone, lightweight connection pool from ServiceStack Redis—it doesn't depend on AppHost or any other ServiceStack components to run.- Registering it as a singleton ensures you reuse a single connection pool across your app, which is the recommended pattern for efficient Redis client usage.
- This plays perfectly with your existing IOC container (like ASP.NET Core's built-in one) so you never have to mix in ServiceStack's DI system.
Quick Usage Example
Once registered, you can inject either IRedisClientsManager or IRedisClient into your services or controllers:
public class ProductCacheService { private readonly IRedisClient _redisClient; public ProductCacheService(IRedisClient redisClient) { _redisClient = redisClient; } public async Task CacheProductAsync(int productId, Product product) { await _redisClient.SetValueAsync($"product:{productId}", product); } }
内容的提问来源于stack exchange,提问作者Sawrub
相关产品推荐
相关产品推荐

