[英]Can I directly Inject ILogger without LoggerFactory
From the IoC perspective, we should be able to easily setup and choose the implementation of a interface.从 IoC 的角度来看,我们应该能够轻松设置和选择接口的实现。
If I create custom implementation of ILogger
, can I directly injected it to controller without the ILoggerFactory-ILoggerProvider-ILogger
structure?如果我创建
ILogger
自定义实现,是否可以将它直接注入控制器而不使用ILoggerFactory-ILoggerProvider-ILogger
结构?
In this way I can have less setting overhead and more control on the Logger.通过这种方式,我可以减少设置开销并更好地控制 Logger。 For example, I can cast and access the
CustomProperty
.例如,我可以投射和访问
CustomProperty
。 In contrast, the logger created by ILoggerFactory-ILoggerProvider-ILogger
chain will maintain a collection of ILogger
s and I can not access my CustomLogger
any more.相比之下,由
ILoggerFactory-ILoggerProvider-ILogger
链创建的记录器将维护一个ILogger
的集合,我无法再访问我的CustomLogger
。
The code will look like below.代码如下所示。 Is this a feasible solution?
这是一个可行的解决方案吗?
Define CustomLogger定义自定义记录器
public class CustomLogger : ILogger
{
public CustomPropertyType CustomProperty;
public CustomLogger(){...}
public IDisposable BeginScope<TState>(TState state){...}
public bool IsEnabled(LogLevel logLevel){...}
public void Log<TState>(
LogLevel logLevel,
EventId eventId,
TState state,
Exception exception,
Func<TState, Exception, string> formatter)
{
// Use some info from CustomProperty in while sending the log
}
}
Setup the Dependency Injection设置依赖注入
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ILogger, CustomLogger>();
//Other logic
}
Access the ILogger
with CustomLogger
implementation使用
CustomLogger
实现访问ILogger
public ExampleController(ILogger logger)
{
this.logger = logger;
this.customProperty = (CustomLogger)logger.CustomProperty;
}
Yes, you need a provider.是的,您需要提供者。 You can add this in the
Startup
class of your .NET Core application.您可以将其添加到 .NET Core 应用程序的
Startup
类中。 Such code shall look like this:此类代码应如下所示:
loggerFactory.AddProvider(new CustomLoggerProvider(new CustomLoggerConfiguration()));
Here is an explanation of such usage. 这是对这种用法的解释。 And here is an example.
这是一个例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.