如何將ILogger注入EFCore DbContext

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(創建記錄器)?

一般承認的答案

您需要做的就是將ILoggerFactoryILogger參數添加到上下文構造函數中:

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

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


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow