C#C
C#11mo ago
Jacko

How to configure services in my cli application:

 var container = new ContainerBuilder()
            .WithSystemConfiguration()
            .WithConsoleVerbosityWriter()
            .WithSystemServices()
            .WithPlugins();
So I have code like above where I'm creating a container using autofac and then registering some services with methods like

public static ContainerBuilder WithConsoleVerbosityWriter(this ContainerBuilder container)
    {
        var logger = new LoggerConfiguration()
            .MinimumLevel.Verbose()
            .Enrich.FromLogContext()
            .WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss} {SourceContext:l} {Level:u3}] {Message:lj}{NewLine}{Exception}")
            .CreateLogger();
        container.RegisterInstance(logger).As<ILogger>();
        return container;
    }
The issue is I want the logger to get its configuration details from the IConfiguraton supplied by WithSystemConfiguration() and I'm not sure whether to use a build callback like

{
        container.RegisterBuildCallback(scope =>
        {
            var config = scope.Resolve<IConfiguration>();
            var logger = new LoggerConfiguration()
                .ReadFrom.Configuration(config)
                .WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss} {SourceContext:l} {Level:u3}] {Message:lj}{NewLine}{Exception}")
                .CreateLogger();

            Log.Logger = logger; // Set the static Serilog logger
            scope.Resolve<ILoggerFactory>().AddSerilog(logger); // Add Serilog to ILoggerFactory
or create a wrapper class like MyCustomLogger that uses ILogger and IConfiguration in it's constructor
Was this page helpful?