简体   繁体   中英

ASP.NET Core DI inside a singleton class

I have a SvcPool class which registers as a singleton service,

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

SvcPool will initialize several Svc based on config inside constructor, but the Svc class constructor need a ILogger.

How to DI a ILogger to Svc's constructor?

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, ???);
    }        
}

You can use ILoggerFactory and create ILogger instances when instantiating 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>());
    }
}

I think you have three options. I've ordered them in the order that I think is best->worst, but use the one that works for you.

1 - Create a factory for 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 - Register a factory which you can inject into SvcPool as 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 - Inject IServiceProvider into SvcPool , and use the service locator anti-pattern to resolve a new instance of ILogger<svc>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM