Mar*_*ark 3 c# dependency-injection redis stackexchange.redis asp.net-core
我正在使用StackExchange.Redis从 .NET Core 连接到 Redis 服务器。如何将单例注入IConnectionMultiplexer另一个单例服务?
启动文件
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect(GetRedisConnectionString()));
services.AddSingleton<IMyService>(new MyService(new DbContext(optionsBuilder.Options)), ???);
...
}
Run Code Online (Sandbox Code Playgroud)
我的服务.cs
private DbContext _dbContext;
private IConnectionMultiplexer _redis;
public MyService(DbContext dbContext, IConnectionMultiplexer redis)
{
_dbContext = fitDBContext;
_redis = redis;
}
Run Code Online (Sandbox Code Playgroud)
我需要放什么而不是放进???去ConfigureServices?还有其他方法吗?
StackExchange.Redis建议(链接)我们保存ConnectionMultiplexer.Connect(...)调用的返回值并重用它。因此,我为它创建了单例服务(它基于另一个StackOverFlow 问题)可以注入,但我没有任何运气将它注入另一个 SINGLETON 服务MyService。
您可以AddSingleton在注册服务时使用工厂委托重载
public void ConfigureServices(IServiceCollection services) {
//...
services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect(GetRedisConnectionString()));
services.AddSingleton<IMyService>(serviceProvider =>
new MyService(new DbContext(optionsBuilder.Options), serviceProvider.GetRequiredService<IConnectionMultiplexer>())
);
//...
}
Run Code Online (Sandbox Code Playgroud)
委托传入IServiceProvider可用于解析所需服务的 。
| 归档时间: |
|
| 查看次数: |
2412 次 |
| 最近记录: |