-
Notifications
You must be signed in to change notification settings - Fork 57
Using multiple DbContexts
For standard applications you typically have one EF Core DbContext that covers the whole of the database. All your code uses that single DbContext to access the database. But in more complex/larger applications you might want to apply the Domain-Driven Design (DDD) concept called Bounded Contexts.
There are lots of sub-concepts of DDD's Bounded Context, but here I want to focus on using multiple DbContexts to cover one, or many databases. The diagram below, taken from section 10.6 of my book "Entity Framework Core in Action" shows one database covered by multiple DbContexts

You need to do two things:
- Setup GenericBizRunner: typically via NET Core's dependency injection (DI) provider (there is a NonDi approach too for serverless).
- Get a instance of GenericBizRunner's
ActionService/ActionServiceAsync. - Write your business logic in the normal way.
In the ConfigureServices method inside the Startup class you should call the following method (V3)
services.RegisterGenericBizRunnerMultiDbContext(
Assembly.GetAssembly(typeof(WebChangeDeliveryDto)),
... other assemblies that contain DTOs );NOTE: You can register both the single version of GenericBizRunner AND the MultiDbContext version of GenericBizRunner - they can work alongside each other.
Here is an example of injecting a multi-DbContext version of the ActionService. You define the DbContext that you want to use with this action.
public IActionResult PlaceOrder(PlaceOrderInDto dto,
[FromServices]IActionService<MyDbContext1, IPlaceOrderAction> service)
{
//rest of code left outThere is no change to your business logic to work with GenericBizRunner's multi-DbContext system (see writing your business logic. You just have to make sure your business logic uses the same DbContext type that you used in the IActionService<TDbContext, TBizInstance> DI call.