简体   繁体   English

如何将 ILogger 注入 EFCore DbContext

[英]How to inject ILogger into EFCore DbContext

I have .net core app with EFCore db context:我有 .net 核心应用程序和 EFCore 数据库上下文:

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

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

In startup class I registered context:在启动 class 中,我注册了上下文:

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

How to inject into MyappDbContext , ILogger or ILoggerFactory (to create logger)?如何注入MyappDbContextILoggerILoggerFactory (创建记录器)?

All you need to do is add a ILoggerFactory or ILogger parameter to the context constructor:您需要做的就是将ILoggerFactoryILogger参数添加到上下文构造函数中:

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

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

In case if you need to instantiate the dbcontext manually:如果您需要手动实例化 dbcontext:

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:但我建议改用 DI:

public void ConfigureServices(IServiceCollection services)
{
            services.AddDbContext<MyDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("Default")).UseLoggerFactory(logFactory));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM