Home > Net >  Injecting IConfiguration into Serilog Setup
Injecting IConfiguration into Serilog Setup

Time:12-30

I building a console app using .NET 6 with DI by using Host.CreateDefaultBuilder.
I'm am also using Serilog for logging and I am facing an inconvenience that I would like to solve while setting up Serilog

Program.cs

IConfiguration configuration = new ConfigurationBuilder()
                              .AddJsonFile("appsettings.json")
                               // .AddUserSecrets<Program>()
                              .Build();

using IHost host =
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration(builder => builder.AddJsonFile("appsettings.json").AddUserSecrets<Program>())
        .UseSerilog(new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger())
        .ConfigureServices(services =>
         {...})
        .Build();

There is code redundancy related to setting up IConfigaration.

Is there a way to use the configuration variable inside ConfigureAppConfiguration() ? Or is it possible to somehow inject the configuration inside UseSerilog so that I don't have to create the configuration variable in the first place?

CodePudding user response:

You can use another overload of the method .UseSerilog() that provides you more input.

Host.CreateDefaultBuilder(args)
    .UseSerilog(ConfigureLogger);

void ConfigureLogger(HostBuilderContext context, LoggerConfiguration loggerConfiguration)
{
    loggerConfiguration.ReadFrom.Configuration(context.Configuration);
}

ConfigureLogger() will be called when the Host is being built. At that point in time, Configuration is already created.

  • Related