单例类中的ASP.NET Core DI

时间:2018-09-11 02:37:31

标签: c# asp.net asp.net-core dependency-injection

我有一个 SvcPool 类,该类注册为单例服务,

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<SvcPool, SvcPool>();
}

SvcPool 将根据构造函数内部的配置初始化多个 Svc , 但是Svc类构造函数需要一个ILogger。

如何将 ILogger 分配给Svc的构造函数?

Svc.cs

public Svc(int id, string host, ILogger<Svc> logger)
{
    ...
}

SvcPool.cs

public SvcPool(IOptions<AppConfig> config, ILogger<SvcPool> logger)
{
    foreach (var svcConfig in config.SvcList)
    {
        Svc svc = new Svc(svcConfig.ID, svcConfig.Host, ???);
    }        
}

2 个答案:

答案 0 :(得分:3)

实例化ILoggerFactory时,可以使用ILogger并创建Svc实例。

public SvcPool(IOptions<AppConfig> config, ILogger<SvcPool> logger, ILoggerFactory loggerFactory)
{
    foreach (var svcConfig in config.Value.SvcList)
    {
        Svc svc = new Svc(svcConfig.ID, svcConfig.Host, loggerFactory.CreateLogger<Svc>());
    }
}

答案 1 :(得分:1)

我认为您有三种选择。我已经按照我认为最好的顺序对它们进行了排序->最差,但是请使用最适合您的那个。

1-为Svc创建工厂:

services.AddSingleton<Svc.Factory>(svcProvider => (id, host) => new Svc(id, host, svcProvider.GetRequiredService<ILogger<Svc>>()));

public class Svc
{
    public delegate Svc Factory(int id, string host);

    public Svc(int id, string host, ILogger<Svc> logger)
    {

    }
}

public SvcPool(IOptions<AppConfig> config, ILogger<SvcPool> logger, Svc.Factory serviceFactory)
{
    foreach (var svcConfig in config.SvcList)
    {
        Svc svc = serviceFactory(svcConfig.ID, svcConfig.Host);
    }
}

2-注册一个可以作为SvcPool注入Func<ILogger<Svc>>的工厂:

services.AddSingleton<Func<ILogger<Svc>>(svcProvider => () => svcProvider.GetRequiredService<ILogger<Svc>>());

public SvcPool(IOptions<AppConfig> config, ILogger<SvcPool> logger, Func<ILogger<Svc>> loggerFactory)
{
    foreach (var svcConfig in config.SvcList)
    {
        Svc svc = new Svc(svcConfig.ID, svcConfig.Host, loggerFactory());
    } 
}

3-将IServiceProvider注入SvcPool,并使用服务定位器反模式来解析ILogger<svc>的新实例