簡體   English   中英

在.net Core中將幫助程序注入DbContext

[英]Injecting helper to DbContext in .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));
    }
}

一旦上下文及其依賴項在容器中注冊

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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM