如何将ILogger注入EFCore DbContext

时间:2017-04-20 11:57:07

标签: dependency-injection entity-framework-core

我有.net核心应用程序与EFCore数据库上下文:

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

    public MyappDbContext(DbContextOptions<MyappDbContext> options)
        : base(options)
    {
        // ???
    }
}

在启动类中我注册了上下文:

services.AddDbContext<MyappDbContext>(options => options.UseSqlServer(connectionString));

如何注入MyappDbContext ILogger或ILoggerFactory(创建记录器)?

1 个答案:

答案 0 :(得分:1)

您需要做的就是在上下文构造函数中添加ILoggerFactoryILogger参数:

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

    public MyappDbContext(DbContextOptions<MyappDbContext> options,
        ILogger<MyappDbContext> logger)
        : base(options)
    {
        _logger = logger;
    }
}