2

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();
Steven
  • 166,672
  • 24
  • 332
  • 435

1 Answers1

2

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)
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • I guess for now I will keep with the option of creating the `ILoggerFactory` as I do not want to use BuildServiceProvider to create a second dependency container just for getting the logger factory instance. Thanks! – Camilo Torres C. Jul 23 '22 at 19:42
  • @CamiloTorresC. Was glad to help! I have not mentioned building service provider option cause in my opinion it is a complete no-no) – Guru Stron Jul 23 '22 at 21:28