ubi
ubi

Reputation: 4399

ILoggerFactory in extension method - lifetime and dispose

To create a ILogger in extension methods I store a ILoggerFactory in 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 set with

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

However, I notice that ILoggerFactory gets disposed

System.ObjectDisposedException: Cannot access a disposed 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 not correct to store a ILoggerFactory? What would be the alternative to access it from extension methods? Store IServiceProvider and GetRequiredService<ILoggerFactory> ?

Upvotes: 4

Views: 3208

Answers (1)

Set
Set

Reputation: 49779

ILoggerFactory will not be added to DI container by default. You should register it using provided AddLogging() extension method.

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

that internally simply do

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

And anyway, as other comments say - try to use built-in DI container as mush as possible instead of own static classes for dependency resolving.

Upvotes: 1

Related Questions