NLog依赖注入 [英] Dependency Injection wth NLog
问题描述
我有一个.NET Core Web应用程序,我正在尝试通过NLog向其中添加日志记录. 在以前的项目中,我只是在每个课程的顶部使用了以下内容:
I've got a .NET Core web app that I'm trying to add logging to via NLog. In previous projects, I've just used something like the following at the top of every class:
private static Logger logger = LogManager.GetCurrentClassLogger();
我正在尝试尽可能多地遵循此项目的最佳实践.
I'm trying to follow more best practices with this project where possible.
我的问题是,我该如何注入一个记录器,该记录器具有要注入的类的完全限定名称?
My question is, how can I inject a logger which has the fully qualified name of the class that it's being injected into?
到目前为止,在我的startup.cs文件中,我具有以下内容:
In my startup.cs file, so far I've got the following:
services.AddScoped<BLL.Logging.NLogLogger>();
目前,NLogLogger
类通过GetCurrentClassLogger()
创建了一个NLog Logger的实例,该实例使用时只会报告名称为"BLL.Logging.NLogLogger".而不是记录器被注入的实际类.
At the moment, the NLogLogger
class creates an instance of an NLog Logger via GetCurrentClassLogger()
, which when used will only ever report the name as "BLL.Logging.NLogLogger" rather than the actual class that the logger is being injected into.
为简化该问题并使之更为通用: 如何传递.NET Core将注入类的类的名称?
To simplify the question and make it a bit more generic: How can you pass in the name of the class that .NET Core is going to inject a class into?
我已经考虑过类似以下的内容,但不确定如何实现:
I've thought about something like the below, but not sure how to achieve it:
services.AddScoped<BLL.Logging.NLogLogger>(serviceProvider => new BLL.Logging.NLogLogger("class name here"));
推荐答案
使用DI指定ILogger<T>
类型而不是Logger
,其中T
是使用记录器的类类型,因此NLog会知道该类.例如:
Using DI specify ILogger<T>
type instead of Logger
, where T
is the class type that uses the logger, so NLog will know about the class. For example:
public class TodoController : Controller
{
private readonly ILogger _logger;
public TodoController(ILogger<TodoController> logger)
{
_logger = logger;
}
}
参考:
- ASP.NET Core入门(csproj vs2017)
获得从ASP.NET Core 2开始 获得从ASP.NET Core 3开始
- Getting started with ASP.NET Core (csproj vs2017)
- Getting started with ASP.NET Core 2
- Getting started with ASP.NET Core 3
这篇关于NLog依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!