A Multi-Data Source Approach to the Generic Repository Pattern
A few months ago, I was working on a project that required me to pull data from two SQL databases to be used in the business logic of an application. I was using Entity Framework as the ORM. While I could have just went the route of instantiating the needed database specific context for every CRUD operation, and write redundant code everywhere; I thought I'd expand on the well known Generic Repository Pattern.
Due to there being two contexts because of the two databases, I essentially needed two RepositoryBase classes to handle each context. However why write the same logic in both? Why not just implement the RepositoryBase class as a true generic class that is Type and Context agnostic, and then have the database specific repository base class pass up the specific context and type. Upon instantiation, the base class will know which context to use and which entity to work with.
It's a lot to unpack in just reading so I decided to add the template code to my Github for those who might run into the same situation.
The synopsis of the change is just adding context specific RepositoryBase classes that can serve as the middleman passing by up context when implementing an entity specific repository(shown in the four screenshots below). Note: This architecture assumes that every Entity contains a primary key named Id in the databases. The EntityBase class is inherited by all Enitities.
Happy Coding!