Reputation: 14846
Does having multiple repositories increase resource usage?
I have followed this tutorial for adding a repository service that holds a database context: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api
In the tutorial the repository is for managing a Todo item. In my own app I have several different types of items and activities that I need a context for. Should I create an individual repository for each? For instance one repository for enquiries, another for user usage metrics? Is there any overhead or penalty for doing this?
Upvotes: 4
Views: 6501
Reputation:
Should I create an individual repository for each? For instance one repository for enquiries, another for user usage metrics? Is there any overhead or penalty for doing this?
Yes. No.
Generally you want to have one repository per entity type because each entity type is going to more than likely require operations specific to its type beyond the cliche CRUD operations. The aim of the repo is to eliminate duplicate data query logic that would otherwise be littered about your application.
e.g.
interface IRepo { CRUD }
protected abstract class RepoBase<T> : IRepo
{
// CRUD implementation
}
public class PatientRepo : RepoBase<Patient>
{
List<IPatient> GetAllTerminallyIllPatients();
}
public class MusicRepo : RepoBase<Music>
{
List<ISong> GetAllSongsByArtist (string artist);
}
Note how each repo in my feeble example is customised to the entity type. If you didn't do this your single repo would quickly
You might want to consider splitting your repos into repos and unit of work classes because:
Repositories should not have semantics of your database. It should be like a collection of objects in memory and should not methods like update and save. - Mosh
You can learn more from the tutorial in the link below.
Does having multiple repositories increase resource usage?
Generally no, because for any given operation, all of your interested repos would be attached to the same database context instance. It is the context that is expensive, not the repo.
Upvotes: 9
Reputation: 11661
As shown in the link provided The Repository pattern can be used to abstract the data access into an interface, in the example: ITodoRepository
.
Why do you abstract data access? This way you could easily switch data-access layer by implementing a different class of ITodoRepository
Say if you want to test your logic with unit tests, or if the possibility exists you wont be using entity framework anymore in the future.
If this is not the case and you are building a small project with no such future additions (unit tests/switch data-access layer) Making use of the Repository pattern is only extra work without any benefits.
So you should decide if the extra work of making the repository pattern outweighs the benefits for your project.
Upvotes: 0