延伸方法中的ILoggerFactory - 生命周期和处置

时间:2017-07-13 06:37:17

标签: c# asp.net-core .net-core asp.net-core-1.0

要在扩展方法中创建ILogger,我将ILoggerFactory存储在静态类中

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);

}

,用

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

但是,我注意到ILoggerFactory被处置

  

System.ObjectDisposedException:无法访问已处置的对象。   对象名称:&#39; LoggerFactory&#39;。       在Microsoft.Extensions.Logging.LoggerFactory.CreateLogger(String categoryName)       在Microsoft.Extensions.Logging.Logger`1..ctor(ILoggerFactory工厂)       在Microsoft.Extensions.Logging.LoggerFactoryExtensions.CreateLogger [T](ILoggerFactory factory)

因此存储ILoggerFactory是不正确的?从扩展方法访问它的替代方法是什么?存储IServiceProviderGetRequiredService<ILoggerFactory>

2 个答案:

答案 0 :(得分:1)

默认情况下,

ILoggerFactory不会添加到DI容器中。您应该使用提供的AddLogging()扩展方法注册它。

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

内部简单地做

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

无论如何,正如其他评论所说的那样 - 尽量使用内置的DI容器,而不是使用自己的静态类进行依赖解析。

答案 1 :(得分:-2)

类似的东西:

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;    
     }
}