Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core inject singleton service in another singleton service

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.

like image 679
Aleks Vujic Avatar asked Oct 18 '25 22:10

Aleks Vujic


1 Answers

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.

like image 101
Nkosi Avatar answered Oct 20 '25 11:10

Nkosi