ASP.NET Core has built-in support for logging, but the documentation states that logging should be done by requesting an ILogger
via dependency injection, i.e. by a
Sharing Bjorn Reppens concerns regarding the accepted answer, and taking Cyprien Autexiers comments into account, I ended up with this (boiled down) solution for "built in DI" without "polluting constructors" in "other classes than the controller" in .NET Core 3.1
Factory:
public class Runtime
{
public static ILogger GetLogger()
{
using var serviceScope = host.Services.CreateScope();
var services = serviceScope.ServiceProvider;
return services.GetRequiredService>();
}
static IHost host;
CancellationTokenSource CancellationSource { get; } = new CancellationTokenSource();
Task hostTask;
public void Start()
{
var hostBuilder = Host.CreateDefaultBuilder();
hostBuilder.ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup());
host = hostBuilder.Build();
hostTask = host.RunAsync(CancellationSource.Token);
}
}
Client:
public class OtherClass
{
ILogger Logger { get; }
public OtherClass() => Logger = Runtime.GetLogger();
}
For further abstraction:
public abstract class LoggerBase
{
protected ILogger Logger { get; }
protected LoggerBase() => Logger = RunTime.GetLogger();
}
e.g.
public class OtherClass : LoggerBase
{
public OtherClass() => Logger.LogInformation("Instantiated");
}