问题描述
我想将 ILogger< MyClass>
的通用实现注入到 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
来自依赖项注入系统,它使用通用类型为logger对象注入正确的Logger名称(通用类型为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< T>作为ILogger使用IServiceCollection和NLog进入构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!