Reputation: 25
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, ???);
}
}
Upvotes: 0
Views: 2512
Reputation: 4553
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>());
}
}
Upvotes: 5
Reputation: 38880
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>
Upvotes: 1