I am using StackExchange.Redis to connect to Redis server from .NET Core. How can I inject singleton IConnectionMultiplexer
to another singleton service?
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect(GetRedisConnectionString()));
services.AddSingleton<IMyService>(new MyService(new DbContext(optionsBuilder.Options)), ???);
...
}
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
? Is there any other approach?
StackExchange.Redis
suggests (link) that we save the returned value of ConnectionMultiplexer.Connect(...)
call and reuse it. 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
.
You can use the factory delegate overload for AddSingleton
when registering the service
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With