Home > database >  Using Autofac in .NET 6 to register ILogger
Using Autofac in .NET 6 to register ILogger

Time:07-18

I am using .NET 6 and the latest version of Autofac for DI in an App Services Worker. So far my Program.cs looks like this:

var builder = new HostBuilder();
builder.UseEnvironment(Environments.Development);

builder.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.ConfigureContainer<ContainerBuilder>(builder => builder.RegisterModule(new 
AutofacModule()));

builder.ConfigureWebJobs(b =>
{
     b.AddAzureStorageCoreServices();
     b.AddAzureStorageQueues();
});

var host = builder.Build();
var logger = host.Services.GetRequiredService<ILogger>();
logger.LogCritical("This is a test");
using (host)
{
    await host.RunAsync();
}

On the line where I try to GetRequiredService, I receive this exception:

enter image description here

What's the proper/easy way to add ILogger to Autofac under .NET 6?

Thank you!

CodePudding user response:

Framework does not register non-generic ILogger, to resolve logger you need to provide generic type parameter for which the logger is used. For top-level statement file it can be generated Program class:

var logger = app.Services.GetRequiredService<ILogger<Program>>();

CodePudding user response:

Try this:

builder.ConfigureContainer<ContainerBuilder>(builder => 
{
  builder.RegisterModule(new AutofacModule());

  builder.RegisterInstance(new LoggerFactory())
            .As<ILoggerFactory>();

   builder.RegisterGeneric(typeof(Logger<>))
      .As(typeof(ILogger<>))
      .SingleInstance();
});
  • Related