在.net Core中将帮助程序注入DbContext

时间:2018-10-22 18:59:32

标签: c# asp.net-core

我正在使用asp.net Core 2.0。我的DbContext如下所示。 AuditHelper是用于记录每个数据库更改的类。因此,我将AuditHelper注入了MyDbContext.cs。但是,我认为这不是正确的方法吗?例如,当我创建MyDbContext的实例时,必须给审计助手参数,例如MyDbContext context = new MyDbContext(null);
我的DbContext风格是真的还是有更好的方法?

public class MyDbContext : DbContext
{
    private readonly IAuditHelper auditHelper;

    public MyDbContext(DbContextOptions<MyDbContext> options, IAuditHelper auditHelper)
        : base(GetOptions())
    {
        this.auditHelper = auditHelper;
    }

    private static DbContextOptions GetOptions()
    {
        return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), "server=asdf; database=asdf; user id=asdf; password=asdf").Options;
    }

    public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
    {
        var audits = auditHelper.AddAuditLog(base.ChangeTracker);
        return (await base.SaveChangesAsync(true, cancellationToken));
    }
}

1 个答案:

答案 0 :(得分:2)

将上下文及其依赖项注册到容器

services.AddScoped<IAuditHelper, AuditHelper>();
services.AddDbContext<MyDbContext>(options => 
    options.UseSqlServer("server=asdf; database=asdf; user id=asdf; password=asdf")
);

然后无需手动初始化(DbContext)

解析注入上下文时,容器将创建对象图。

请注意,如上所述,静态GetOptions功能可以在启动时移至ConfigureServices

让上下文保持简单。

public class MyDbContext : DbContext {
    private readonly IAuditHelper auditHelper;

    public MyDbContext(DbContextOptions<MyDbContext> options, IAuditHelper auditHelper)
        : base(options) {
        this.auditHelper = auditHelper;
    }

    public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken)) {
        var audits = auditHelper.AddAuditLog(base.ChangeTracker);
        return base.SaveChangesAsync(true, cancellationToken);
    }
}