'How to inject ILogger into EFCore DbContext
I have .net core app with EFCore db context:
public class MyappDbContext : DbContext
{
private ILogger<MyappDbContext> _logger;
public MyappDbContext(DbContextOptions<MyappDbContext> options)
: base(options)
{
// ???
}
}
In startup class I registered context:
services.AddDbContext<MyappDbContext>(options => options.UseSqlServer(connectionString));
How to inject into MyappDbContext, ILogger or ILoggerFactory (to create logger)?
Solution 1:[1]
In case if you need to instantiate the dbcontext manually:
public class Startup
{
public static readonly ILoggerFactory logFactory = LoggerFactory.Create(builder => builder.AddDebug());
....
public Startup(IWebHostEnvironment env)
{
....
}
public void ConfigureServices(IServiceCollection services)
{
....
}
}
public class MyDbContext : DbContext
{
private readonly ILoggerFactory _loggerFactory;
public MyDbContext(DbContextOptions<MyDbContext> options,
ILoggerFactory loggerFactory)
: base(options)
{
_loggerFactory = loggerFactory;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLoggerFactory(_loggerFactory);
// optionsBuilder.EnableSensitiveDataLogging();
}
}
// Somewhere else
var db = new MyDbContext(new DbContextOptions<MyDbContext>(), Startup.logFactory);
But I would recommend using DI instead:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("Default")).UseLoggerFactory(logFactory));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ADM-IT |
