Dependency Injection wth NLog

前端 未结 2 1904
醉酒成梦
醉酒成梦 2020-12-31 05:58

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:

相关标签:
2条回答
  • 2020-12-31 06:18

    I think I've figured out an acceptable solution, although not exactly the way I asked the question.

    First of all, I create a "LoggerFactory", which has a single method called "GetLogger" (which creates the concrete NLog Logger and accepts a class name as a parameter), and I inject this factory instead of the logger directly.

    LoggerFactory:

    public class LoggerFactory : ILoggerFactory
    {
        public ILogger GetLogger(string fullyQualifiedClassName)
        {
            return new NLogLogger(fullyQualifiedClassName);
        }
    }
    

    NLogLogger:

    public class NLogLogger : ILogger, INLogLogger
    {
        NLog.Logger mylogger;
        public NLogLogger(string fullyQualifiedClassName)
        {
            mylogger = NLog.LogManager.GetLogger(fullyQualifiedClassName);
        }
    }
    

    Startup.cs:

    services.AddScoped<BLL.Logging.ILoggerFactory>();
    

    The in my controller class, I've got:

        private BLL.Logging.ILogger logger;//my NLogLogger inherits this interface
    
        public HomeController(BLL.Logging.ILoggerFactory loggerFactory)
        {
            logger = loggerFactory.GetLogger(this.GetType().FullName);
        }
    

    So what I've effectively now done, is rather than injecting the actual Logger itself (Which @Steven indicated would not be possible the way I was trying to do it), I've instead injected the utility to create an instance of a logger which wraps NLog.

    I've still got the responsibility to create the logger within the class, but at least I've decoupled from the underlying logging framework (NLog).

    0 讨论(0)
  • 2020-12-31 06:26

    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;
        }
    }
    

    References:

    • Getting started with ASP.NET Core (csproj vs2017)
    • Getting started with ASP.NET Core 2
    • Getting started with ASP.NET Core 3
    0 讨论(0)
提交回复
热议问题