Reputation: 32900
I have the following configuration:
builder.Register<EntityContext>().As(
c=> {
var entityCtx = new EntityContext();
//snip snip: some config stuff
return entityCtx;
}).As<MyDbContext>().InstancePerLifetimeScope();
EntityContext
obviously inherits from MyDbContext
which again inherits from DbContext
.
In my repository's constructor I'm usually using them as
...
public MyRepository(MyDbContext context) {...}
This ensures to have one ctx per http request which is what I want. But now I have the need that for a specific repository I want to have a different instance of the EntityContext than is normally being used.
How would you achieve that? The following came to my mind:
Register<EntityContext>()....As<DbContext>()...
Any other ideas?
Upvotes: 3
Views: 2538
Reputation: 32900
I just found a proper solution that could work, namely to use the OwnedInstances
of AutoFac if I understood correctly. For example:
class MyRepository
{
public MyRepository(Owned<MyDbContext> context, MyDbContext context2)
{
//context and context2 are two different object instances
}
}
This scenario is especially useful if you'd like MyRepository to run in a different transaction, i.e. it needs to have a different DbContext
instance than the other repositories.
Upvotes: 5
Reputation: 364259
Once you have different lifetime requirement you must either use another config or manually call container to give you a new instance of the context (or create context instance directly but that is something you don't want to do when using IoC container).
Upvotes: 2