[英].NET Core inject singleton service in another singleton service
I am using StackExchange.Redis to connect to Redis server from .NET Core. 我正在使用StackExchange.Redis从.NET Core连接到Redis服务器。 How can I inject singleton IConnectionMultiplexer
to another singleton service? 如何将单例IConnectionMultiplexer
注入另一个单例服务?
Startup.cs 启动文件
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect(GetRedisConnectionString()));
services.AddSingleton<IMyService>(new MyService(new DbContext(optionsBuilder.Options)), ???);
...
}
MyService.cs MyService.cs
private DbContext _dbContext;
private IConnectionMultiplexer _redis;
public MyService(DbContext dbContext, IConnectionMultiplexer redis)
{
_dbContext = fitDBContext;
_redis = redis;
}
What do I need to put instead of ???
我需要放什么而不是???
in ConfigureServices
? 在ConfigureServices
? Is there any other approach? 还有其他方法吗?
StackExchange.Redis
suggests ( link ) that we save the returned value of ConnectionMultiplexer.Connect(...)
call and reuse it. StackExchange.Redis
建议( link )我们保存ConnectionMultiplexer.Connect(...)
调用的返回值并重新使用它。 Therefore, I created singleton service for it (it is based on another StackOverFlow question ) which can be injected, but I am not having any luck injecting it to another SINGLETON service MyService
. 因此,我为此创建了单例服务(它基于另一个StackOverFlow问题 ),但是我没有运气将其注入到另一个SINGLETON服务MyService
。
You can use the factory delegate overload for AddSingleton
when registering the service 注册服务时,可以将工厂委托重载用于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>())
);
//...
}
The delegate passes in an IServiceProvider
which can be used to resolve desired services. 委托传入一个IServiceProvider
,该服务可用于解析所需的服务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.