.NET Core在另一个单例服务中注入单例服务 [英] .NET Core inject singleton service in another singleton service

查看:376
本文介绍了.NET Core在另一个单例服务中注入单例服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 StackExchange.Redis 从.NET Core连接到Redis服务器.如何将单例 IConnectionMultiplexer 注入到另一个单例服务?

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;
}

我需要在 ConfigureServices 中放置什么而不是 ??? ?还有其他方法吗?

What do I need to put instead of ??? in ConfigureServices? Is there any other approach?

StackExchange.Redis 建议(链接)我们保存 ConnectionMultiplexer.Connect(...)调用的返回值,然后重用它.因此,我为此创建了单例服务(它基于另一个可以注入StackOverFlow问题),但是我没有运气将其注入到另一个SINGLETON服务 MyService .

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.

推荐答案

注册服务时,您可以对 AddSingleton 使用工厂委托重载

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>())
    );

    //...
}

委托传递了一个 IServiceProvider ,该代码可用于解析所需的服务.

The delegate passes in an IServiceProvider which can be used to resolve desired services.

这篇关于.NET Core在另一个单例服务中注入单例服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆