1

I'm using dotnet core 3.1 and I want to add ILoggerFactory to startup constructor.

But I get an error:

'Unable to resolve service for type 'Microsoft.Extensions.Logging.ILoggerFactory' while attempting to activate 'Startup'.'

My configuration in Program.cs:

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.AddConsole();
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

What should I do?

Saeid Mirzaei
  • 950
  • 2
  • 18
  • 48

1 Answers1

1

You should configure logging in the HTTP request pipeline(your Startup configure method).

eg.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
     //depending on what you use for logging 
   loggerFactory.AddLog4Net();
     //or
   loggerFactory.CreateLogger...
     ...
}
mike
  • 1,202
  • 1
  • 7
  • 20
  • Isn't this incorrect, as the 2.2 dot net core spec specifies to do it in Program.CreateWebHostBuilder via "ConfigureLogging((hostingContext, logging)"? https://learn.microsoft.com/en-us/aspnet/core/migration/21-to-22?view=aspnetcore-6.0&tabs=visual-studio (bottom of the page) – Richard Duerr Feb 22 '22 at 23:05