Unable to resolve ILogger from Microsoft.Extensions.Logging

前端 未结 7 1045
太阳男子
太阳男子 2021-02-02 04:56

I\'ve configured my console application\'s Main like so

var services = new ServiceCollection()
                .AddLogging(logging => logging.Add         


        
7条回答
  •  花落未央
    2021-02-02 05:37

    As noted in a comment, the accepted answer has the problem that BuildServiceProvider should not be used in ConfigureServices, since it creates another copy of each singleton (in fact, of the whole DI container). Here is an alternative one-liner that avoids that problem. In ConfigureServices, add the line

    services.AddSingleton(provider => 
       provider.GetRequiredService>());
    

    where AnyClass can be any class, as explained in the accepted answer. This redirects the resolution of ILogger to that of ILogger.

    Like the accepted answer, this one has the disadvantage that Serilog's SourceContext will be set to AnyClass. So, if your Serilog configuration contains an outputTemplate that contains {SourceContext}, your log will show AnyClass instead of the class that contains the logging statement.

提交回复
热议问题