Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I initialize an ILogger in a .NET 6 class library?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

c# online

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading