ILoggerFactory in extension method - lifetime and disposal

To create ILoggerin extension methods, I save ILoggerFactoryin a static class

public static class ApplicationLogging
{
    public static ILoggerFactory LoggerFactory { get; set; }

    public static ILogger CreateLogger<T>() =>
        LoggerFactory?.CreateLogger<T>();

    public static ILogger CreateLogger(string name) =>
        LoggerFactory?.CreateLogger(name);

}

which is installed using

public void Configure(ILoggerFactory loggerFactory)
{
   ...
    ApplicationLogging.LoggerFactory = loggerFactory;
}

However, I notice that ILoggerFactoryit is getting the location

System.ObjectDisposedException: Unable to access the remote object. Object Name: "LoggerFactory". at Microsoft.Extensions.Logging.LoggerFactory.CreateLogger (String categoryName) at Microsoft.Extensions.Logging.Logger`1..ctor (ILoggerFactory factory) at Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger [T] (ILoggerFactory factory)

So is it right to store ILoggerFactory? What is the alternative to access it from extension methods? Store IServiceProviderand GetRequiredService<ILoggerFactory>?

+4
2

ILoggerFactory DI. AddLogging().

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddLogging()
}

services.TryAdd(ServiceDescriptor.Singleton<ILoggerFactory, LoggerFactory>());

, , DI , .

+1

- :

public class MyClass
{
    private readonly ILogger _logger;
    public MyClass(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger<MyClass>();
        "Test".ToSomething(_logger);
    }

     public static string ToSomething(this string source, ILogger logger)
     {
        logger.LogInformation(source);
        return source;    
     }
}
-1

Source: https://habr.com/ru/post/1681331/


All Articles