How to get ILoggerFactory instance in .NET 6 Program.cs class

1.7k views Asked by At

In .NET 5 ILoggerFactory can be accessed in the Startup constructor as follows:

public Startup(
    IConfiguration configuration,
    IHostEnvironment hostEnvironment,
    ILoggerFactory loggerFactory)
{
     LoggerFactory = loggerFactory;
     Configuration = configuration;
     HostEnvironment = hostEnvironment;
}

I just have a custom package that receives as a parameter the ILoggerFactory instance

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddCustomMvc(Configuration, loggerFactory: LoggerFactory);
}

In .NET 6 how can I get the ILoggerFactory before the app.Build() like this

var builder = WebApplication.CreateBuilder(args);

var configuration = builder.Configuration;

builder.Services.AddCustomMvc(configuration, loggerFactory: loggerFactory);

var app = builder.Build();

app.Run();
1

There are 1 answers

2
Guru Stron On BEST ANSWER

I'm afraid that there is not much options except creating ILoggerFactory manually (as done to log in top-level statement Program file):

using var loggerFactory =
    LoggerFactory.Create(lb => lb.AddConfiguration(builder.Configuration));

builder.Services.AddCustomMvc(configuration, loggerFactory: loggerFactory);

Which will require you to repeat the logging setup.

Other options:

  • switch back to the generic hosting
  • rework AddCustomMvc approach so there would be no need to pass the loggerFactory (change registrations to resolve from IServiceProvider)