How to register ILogger for injection in ASP.NET MVC 6

前端 未结 3 2054
你的背包
你的背包 2021-02-06 20:55

I have a ASP.NET MVC 6 (beta-4) app.

public void ConfigureServices(IServiceCollection services)
{
    // Logging
    services.AddLogging();

    // ...
}

publi         


        
相关标签:
3条回答
  • 2021-02-06 21:43

    The services.AddLogging(); didn't worked for me, so I added these two statements to ConfigureServices:

    services.AddSingleton<ILoggerFactory, LoggerFactory>();
    services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
    

    Now the DI container is happy and everything works.

    0 讨论(0)
  • 2021-02-06 21:50

    I assumed that services.AddLogging(); was doing the right thing and registering ILogger. After looking at the source (https://github.com/aspnet/Logging/blob/d874c5726e713d3eb34938f85faf7be61aae0f2a/src/Microsoft.Framework.Logging/LoggingServiceCollectionExtensions.cs) I found that it's actually registering ILogger<>. Changing the signature of ILogger to ILogger<HomeController> makes the above example work.

    public class HomeController : 
        Controller
    {
        ILogger<HomeController> _logger;
    
        public HomeController(ILogger<HomeController> logger) 
        {
            _logger = logger;
        }
    
        // ...
    }
    

    Thanks to @Steve for setting me on the right track to find this.

    0 讨论(0)
  • 2021-02-06 21:53

    just add this line to ConfigureServices

    services.AddSingleton(Serilog.Log.Logger);
    
    0 讨论(0)
提交回复
热议问题