Using Multiple DbContext on .NET 6 Web API With Repository Pattern
Hello, I this article, I will show how to use of multiple DbContext in an ASP.NET Web API (.NET 6.0) project. We will connect to 2 different databases by changing the DbContext. Now let’s create ASP.NET Web API (.NET 6) project. Secondly, we will install the EntityFramework packages.
We will create the DbContext classes when the package installation is complete. Create three classes are named DbOneContext, DbTwoContext and BaseContext to the Data folder.
We will update DbOneContext and DbTwoContext concrete classes which inherits BaseContext.
After creating the DbContext classes, we will add DbOneContext and DbTwoContext are connectionstrings to the appsettings.json file.
We will add DbContext classes info to Program.cs file.
Create a Models named folder and add a Book class.
Then we will add the Book entity class in BaseContext.
We will create a class called DbContextFactory in the Data folder. In this class we will return the BaseContext object with the contextName value inside an IDictionary. In this way, we will have made a development in accordance with SOLID principles.
Now we can create the Repository structure. Create IBookRepository interface under the Repository folder.
We will select DbContext with the ContextName parameter.
In this class, we will move the DbContextFactory and DbContext objects into the Repository in the constructor. We can access the DbContext sent with the parameter. We will add the AutoFac IOC container to the project.
After downloading the package, we will immediately configure AutoFac in Program.cs.
We will add the AutoFacModule class.
After AutoFac IOC configuration, we will add a Web API controller named BookController to the controllers folder.
We select the dbContext with the contextName parameter. We will do CRUD operations with BookRepository. After creating the controller, we will create the DbOne and DbTwo databases with Migration. Since there are multiple DbContext files, it is necessary to specify which one to create in the migration process.
After the migration;
We will do CRUD operations with Swagger. We will do Post and Get requests for DbOneContext.
We will perform CRUD operations on the DbTwo database with the DbTwoContext parameter.
You can download the project here. Please let me know if there are typos in my post.
Note: This article and sample project files have been rearranged according to SOLID principles with Amrelsher’s contributions.