I created an ASP.NET Core 3.0 Web Application with the default template in Visual Studio 2019 Preview 2.2 and tried to inject an ILogger in Startup:
namespace We
If you want to log things after the Configure() has been called, you can still inject the ILogger via method injection (as opposed to the preferred constructor injection:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<TStartup> logger)
{
_logger = logger;
...
}
This issue is related with IHostBuilder
.
For a temp workaround, I suggest you try IWebHost
to replace IHostBuilder
.
Change your Program.cs like
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
})
.Build();
}
Did you have using ServiceCollection to register the Logger yet! It's should be here.
serviceProvider.AddTransient(typeof(ILogger<>), (typeof(Logger<>));
or you put, this is sample for Program.cs
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging(logging => logging.SetMinimumLevel(LogLevel.Warning))
.UseStartup<Startup>()
.Build();
}
This can be solved by registering the ILogger
manually to use the Startup class as type.
Example:
public void ConfigureServices(IServiceCollection services)
{
// Normal AddLogging
services.AddLogging();
// Additional code to register the ILogger as a ILogger<T> where T is the Startup class
services.AddSingleton(typeof(ILogger), typeof(Logger<Startup>));
// ...
}
Unfortunately, it's not possible to inject ILogger
into Startup.cs in ASP.NET Core 3.0 anymore.
https://docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger#capture-ilogger-logs-from-startupcs-and-programcs-in-aspnet-core-apps
Note
In ASP.NET Core 3.0 and later, it is no longer possible to inject ILogger in Startup.cs and Program.cs. See https://github.com/aspnet/Announcements/issues/353 for more details.