.NET Core 在另一个单例服务中注入单例服务

.NET Core inject singleton service in another singleton service

我正在使用 StackExchange.Redis 从 .NET Core 连接到 Redis 服务器。如何将单例 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

private DbContext _dbContext;
private IConnectionMultiplexer _redis;

public MyService(DbContext dbContext, IConnectionMultiplexer redis)
{
    _dbContext = fitDBContext;
    _redis = redis;
}

我需要在 ConfigureServices 中输入什么来代替 ????还有其他方法吗?

StackExchange.Redis 建议 (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 ) 可以注入,但我没有运气将它注入另一个 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>())
    );

    //...
}

代表传入一个IServiceProvider,可用于解析所需的服务。