I want to use the LoggerFactory from the CoreOptionsExtension .
public class MyContext : DbContext
{
private readonly ILogger<MyContext> logger;
public MyContext(DbContextOptions options) : base(options)
{
logger = options.FindExtension<CoreOptionsExtension>()?.LoggerFactory?.CreateLogger<MyContext>();
if (logger == null)
{
throw new Exception("Logger required.");
}
}
}
This will throw the exception:
services.AddDbContext<MyContext>();
This does work but then the documentation states:
// There is no need to call this method when using one of the 'AddDbContext' methods,
// including 'AddDbContextPool'. These methods ensure that the Microsoft.Extensions.Logging.ILoggerFactory
// used by EF is obtained from the application service provider.
services.AddDbContext<MyContext>((serviceProvider, optionsBuilder) =>
{
optionsBuilder.UseLoggerFactory(serviceProvider.GetService<ILoggerFactory>());
});