I’ve a class library, which is used by a console application. I now want to add a ILogger<T> via constructor injection in my class library. I came up with something like this:
public class Class1
{
private readonly ILogger<Class1> _logger;
public Class1(ILogger<Class1> logger)
{
_logger = logger;
}
}
Nevertheless I don’t know how I could hand over the ILogger<T>.
public class Program
{
public static void Main(string[] args)
{
Class1 clazz = new Class1(?????);
}
}
>Solution :
We can try to use ServiceCollection which can be restored from Microsoft.Extensions.DependencyInjection
ServiceCollection can register Class1 class to DI Container and ILogger<Class1> might auto injected if we register our class correctly.
var services = new ServiceCollection();
services.AddLogging(configure => configure.AddConsole());
services.AddTransient<Class1>();
ServiceProvider serviceProvider = services.BuildServiceProvider();
Class1 clazz = serviceProvider.GetRequiredService<Class1>();
I would suggest using Microsoft.Extensions.Logging to implement our log mechanism which provides infrastructure default implementation by Microsoft.