使用NLog进行依赖注入 [英] Dependency Injection With NLog
问题描述
我有一个.Net核心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've 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 big 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;
}
}
这篇关于使用NLog进行依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!