C# – How to design the repositories when there are multiple sources for the same sort of data

cdesign-patternsrepository

In my application, I have to get data from our ERP. For this example, let's say product data.

Some of the data will come from the API that our ERP has provided us, whilst some of it will come from direct DB calls as the API doesn't give us all the required detail.

For this situation, do I just do with a single Repository and within the repository methods I get the data from the required place?

If I do this, my concern is that I will be injecting into the constructor IApiService as well as database connection strings which depending on the data I am retrieving, it may not be necessary.

Do I create 2 separate repository, something like ApiProductRepository and DatabaseProductRepository?

Some guidance on the best methods here would be great!

Best Answer

I would create two separate implementations of the repository interface like ApiProductRepository and DatabaseProductRepository. Each implementation will throw an NotSupportedException for methods that it doesn't support. Finally create a ErpRepository that takes an ApiProductRepository and DatabaseProductRepository and invokes the appropriate implementation based on the method.

Here is a class diagram describing how I would design the solution

enter image description here

Edit: I was answering under the assumption that some methods would be provided by the DB and some by the API. After OP clarified that some attributes of the model will be filled from the API and some will be filled by the DB, the design above doesn't cover that case well, and I would use the simpler design:

enter image description here

Related Topic