How to get Microsoft.Extensions.Logging in console application using Serilog and AutoFac?

前端 未结 3 1595
悲哀的现实
悲哀的现实 2021-02-12 14:31

We have common BL classes in a ASP.NET Core application that get in the ctor:

Microsoft.Extensions.Logging.ILogger

In ASP.NET Core, the i

3条回答
  •  南笙
    南笙 (楼主)
    2021-02-12 15:20

    In Console app Main method

    var builder = new ConfigurationBuilder()
                 .SetBasePath(Directory.GetCurrentDirectory())
                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                 .AddEnvironmentVariables();
            IConfigurationRoot configuration = builder.Build();
    
            var serviceProvider = new ServiceCollection()
                    .AddDbContext(optionns => optionns.UseSqlServer(configuration.GetConnectionString("connectionString")))
                    .AddSingleton(typeof(ILogger<>), typeof(Logger<>))
                    .AddLogging() 
                    .BuildServiceProvider();
    
            MyDbContext _context = serviceProvider.GetService();
            var _logger = serviceProvider.GetService>();
    

提交回复
热议问题