Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to use a generic repository or should each entity have its own repository?

Being fairly new to Asp.Net MVC I am following the SportsStore example from the book Pro ASP.Net MVC 3 Framework.

All is going fine, but now I start to enhance the base example with some extra entities. Which is the better approach: - should each entity have its own repository (which would seem to duplicate code) or - should there be a generic repository for similar entities?

Are there any other projects out there that the same architecture are more complete samples?

like image 785
simon831 Avatar asked Jun 18 '12 16:06

simon831


People also ask

Why would you implement a generic repository?

It reduces redundancy of code. It force programmer to work using the same pattern. It creates possibility of less error. If you use this pattern then it is easy to maintain the centralized data access logic.

Does every entity need a repository?

It depends on your logic and how "important" are every entity. For example, if you had the entities User and Address you could have UserRepository and AddressRepository. But only UserService, with methods like addAddress(User user, Address address)... Save this answer.

What is generic repository?

It is a data access pattern that prompts a more loosely coupled approach to data access. We create a generic repository, which queries the data source for the data, maps the data from the data source to a business entity, and persists changes in the business entity to the data source.

What are the benefits of using the repository pattern?

The Repository pattern makes it easier to test your application logic. The Repository pattern allows you to easily test your application with unit tests. Remember that unit tests only test your code, not infrastructure, so the repository abstractions make it easier to achieve that goal.


1 Answers

This is something that is heavily debated on the internet. If you use the search here at SO you can find plenty of threads about it. In the end is just comes down to your personal preference. Try both options and decide which one is best for you.

I started creating separate repositories for every entity, but it felt like loads of unnecessary work (and lots of code duplication), so recently I started using generic repositories, and that's working out perfectly for me.

See this thread for more information: Advantage of creating a generic repository vs. specific repository for each object?

like image 97
Leon Cullens Avatar answered Oct 26 '22 20:10

Leon Cullens