如何注入命名记录器泛型 ILogger<T>使用 IServiceCollection 和 NLog 作为 ILogger 进入构造函数 [英] How to inject named logger generic ILogger<T> as ILogger into constructor using IServiceCollection and NLog

查看:46
本文介绍了如何注入命名记录器泛型 ILogger<T>使用 IServiceCollection 和 NLog 作为 ILogger 进入构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 ILogger 的通用实现注入到 MyClass 的构造函数中,而没有它的通用参数.

I want to inject the generic implementation of ILogger<MyClass> into the constructor of MyClass without its generic parameters.

示例:

public class MyClass
{
  private readonly ILogger _logger;

  // Inject ILogger<MyClass> as type ILogger
  public MyClass(ILogger logger) 
  {
    _logger = logger;
  }
}

我基本上不想每次都编写它的泛型类型,并且希望自动解决它.使用 autofac 我已经能够解决这个问题,但由于一些限制,它不可能使用 autofac.

I basically dont want to write its generic type everytime and would want to have it automagically resolved. Using autofac I've been able to resolve this though due to some constraints its not possible to use autofac.

     services.AddLogging(configure =>
     {
       configure.ClearProviders();
       configure.SetMinimumLevel(LogLevel.Trace);
       configure.AddNLog();
     });

推荐答案

ILogger 来自依赖注入系统,它使用泛型类型为记录器对象注入正确的记录器名称(来自泛型类型的 NameSpace.ClassName).

The ILogger comes from the dependency-injection-system, and it uses the generic-type to imbue the logger-object with the correct Logger-name (NameSpace.ClassName from the generic-type).

你可以这样做:

public class MyClass
{
  private readonly ILogger _logger;   // Notice no generic

  public MyClass(ILogger<MyClass> logger) 
  {
    _logger = logger;
    _logger.LogInformation("Hello");
  }
}

或者你可以这样做:

public class MyClass
{
  private readonly ILogger _logger;   // Notice no generic

  public MyClass(ILoggerFactory loggerFactory) 
  {
    _logger = loggerFactory.CreateLogger(GetType().ToString());  // Performance hit
    _logger.LogInformation("Hello");
  }
}

如果你不喜欢 MEL-ILogger,那么你可以直接使用 NLog-Logger:

If you don't like MEL-ILogger, then you can just use NLog-Logger directly:

public class MyClass
{
  private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();

  public MyClass() 
  {
    Logger.Info("Hello");
  }
}

这篇关于如何注入命名记录器泛型 ILogger&lt;T&gt;使用 IServiceCollection 和 NLog 作为 ILogger 进入构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆