Is it better to have a repository per model (this could be a class that represents a table from the database) or should just have one big repository for all data access methods?

I have done the second approach and have found it to get way out of hand, but maybe somewhere in between is a solution as well.


Why are repositories any different from other classes?

A class should have a single responsibility - a single reason to change. If you have a bundle of related data sources that are (necessarily) tightly coupled, then it can make sense to have a single repo to deal with all of them. If you have some unrelated tables, then it's probably better to have a single repository per table.

  • Thanks. Sometimes the hard part is finding out what is the related/unrelated data especially if you don't know the business side of it. Also, related and unrelated data can have different meanings to different people. Appreciate the answer. – xaisoft Mar 16 '15 at 13:30
  • @xaisoft - when in doubt, assume it's unrelated. – Telastyn Mar 16 '15 at 13:57

Implementing repositories "by the book" will typically mean to create one per entity or table (see here, for example). However, when your entities are uniform, and all of your repositories look very similar, it can make sense to implement a generic repository class (just as shown in the former link). That will probably be the better alternative for avoiding too much boiler plate code than the "big-ball-of-mud" repo.

Nevertheless, Fowler's description of the repository pattern does not explicitly require to have one repo per entity. So I agree to Telastyn: when there is bundled data, which has to be pulled and pushed always together in one query or transaction, it can make more sense to have one repo for more than one table.


Eric Evans Domain Driven Design specifies that you should provide a repository for 'aggregate roots' that need direct access. So this is not one repository per model but one repository per cluster of models, if you like. This assumes you are doing DDD and therefore understand the business context, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.