AutoFac LifeTime:在特定情况下强制创建新实例

Jur*_*uri 3 c# inversion-of-control autofac entity-framework-4

我有以下配置:

builder.Register<EntityContext>().As(
   c=> {
       var entityCtx = new EntityContext();
       //snip snip: some config stuff

       return entityCtx;
   }).As<MyDbContext>().InstancePerLifetimeScope();
Run Code Online (Sandbox Code Playgroud)

EntityContext显然继承自MyDbContext又继承自DbContext.

在我的存储库的构造函数中,我通常将它们用作

...
public MyRepository(MyDbContext context) {...}
Run Code Online (Sandbox Code Playgroud)

这确保每个 http 请求都有一个 ctx,这正是我想要的。但是现在我需要一个特定的存储库,我想要一个不同于通常使用的 EntityContext实例

你会如何做到这一点?我想到了以下几点:

  • 我使用的另一个配置 Register<EntityContext>()....As<DbContext>()...

还有其他想法吗?

Jur*_*uri 5

我刚刚找到了一个可行的正确解决方案,即OwnedInstances如果我理解正确,则使用AutoFac 。例如:

class MyRepository
{
    public MyRepository(Owned<MyDbContext> context, MyDbContext context2)
    {
        //context and context2 are two different object instances
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您希望 MyRepository 在不同的事务中运行,则此方案特别有用,即它需要具有DbContext与其他存储库不同的实例。