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

前端 未结 3 1591
悲哀的现实
悲哀的现实 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:08

    I would recommend a slightly different approach if you want to register ir manually direct on Autofac:

    private static void ConfigureLogging(ILoggingBuilder log)
    {
        log.ClearProviders();
        log.SetMinimumLevel(LogLevel.Error);
        log.AddConsole();
    }
    
    private static void ConfigureContainer(ContainerBuilder builder)
    {
        builder.Register(handler => LoggerFactory.Create(ConfigureLogging))
            .As()
            .SingleInstance()
            .AutoActivate();
    
        builder.RegisterGeneric(typeof(Logger<>))
            .As(typeof(ILogger<>))
            .SingleInstance();
        // other registrations
    }
    

    And this on you main startup code:

    var containerBuilder = new ContainerBuilder();
    ConfigureContainer(containerBuilder);
    
    var container = containerBuilder.Build();
    var serviceProvider = new AutofacServiceProvider(container);
    // you can use either the built container or set the serviceProvider onto the library you are using.
    

提交回复
热议问题