How to inject ILogger into EFCore DbContext

c# dependency-injection entity-framework-core

Question

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)?

1
1
11/21/2019 2:03:03 PM

Accepted Answer

All you need to do is add a ILoggerFactory or ILogger parameter to the context constructor:

public class MyappDbContext : DbContext
{
    private readonly ILogger<MyappDbContext> _logger;

    public MyappDbContext(DbContextOptions<MyappDbContext> options,
        ILogger<MyappDbContext> logger)
        : base(options)
    {
        _logger = logger;
    }
}
2
4/20/2017 12:07:59 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow