使用Simple Injector注册多个DbContext

时间:2017-04-19 13:14:24

标签: c# entity-framework simple-injector

我的应用程序中有两个派生的DbContext类型:

  • MyDbContext映射到我可以控制的数据库
  • ExternalDbContext映射到我无法控制的数据库(这是新的,需要添加)

在应用程序中,我还使用了Decorator pattern,其中我有一个包含业务逻辑的SaveChangesDecorator类。此装饰器注入了DbContext类型,并在其上调用.SaveChanges()方法。

public class SaveChangesDecorator : IWhatever
{
    private readonly DbContext dbContext;
    private readonly IWhatever decoratee;

    public SaveChangesDecorator(DbContext dbContext, ...)
    {
         this.dbContext = dbContext;
         ...
    }

    public void Whatever()
    {
         this.decoratee.Whatever()
         this.dbContext.SaveChanges();
    }
}

现在它取决于在业务逻辑中注入派生的DbContext(或两者)的用例。我有以下注册:

var databaseContextRegistration = scopedLifestyle.CreateRegistration(
    () => new MyDbContext(connectionString), container);

container.AddRegistration(typeof(MyDbContext), databaseContextRegistration);
container.AddRegistration(typeof(DbContext), databaseContextRegistration);

现在我无法在注册中添加ExternalDbContext,因为这样做会很模糊。最好的选择是将DbContext注册为此场景的集合吗?

1 个答案:

答案 0 :(得分:4)

  

现在我无法在注册中添加ExternalDbContext,因为这样做会很模糊。

ExternalDbContext注册为DbContext不仅在您的注册中含糊不清,在您的申请中也不明确,因为DbContext取决于Liskov Substitution Principle违规,假设{ {1}}具有不同的架构。

如果它有不同的架构,那么使用ExternalDbContext并期望您的正常'如果您向DbContext提供数据库,数据库将会中断。

这通常意味着您为每个上下文提供了自己的界面'这就是您正在做的事情。因此,我的建议是丢失ExternalDbContext注册,只需注册DbContextExternalDbContext,并在装饰器中注入两个实例。