90

I am wondering how should I be grouping my repositories? Like from the examples I seen on the ASP.NET MVC and in my books they basically use one repository per database table. But that seems like a lot of repositories leading you to have to call up many repositories later on for mocking and stuff.

So I am guessing I should group them. However I am not sure how to group them.

Right now I made a registration Repository to handle all my registration stuff. However, there are like four tables I need to update and before I had three repositories to do this.

For example, one of the tables is a license table. When they register I look at their key and check it to see if exists in the database. Now what happens if I need to check this license key or something else from that table at some other spot other then registration?

One spot could be login (check if the key is not expired).

So what would I do in this situation? Rewrite the code again (break DRY)? Try to merge these two repositories together and hope that none of the methods are needed in some other point of time(like maybe I might have a method that checks if userName is used - maybe I will need that somewhere else).

Also if I merge them together I would either need two service layers going to the same repository since I think having all the logic for two different parts of a site would be long, and I would have to have names like ValidateLogin(), ValdiateRegistrationForm(), ValdiateLoginRetrievePassword(), etc.

Or call the Repository anyway and just have a weird sounding name around?

It just seems hard to make a repository that has a general enough name so you can use it for many spots of your application and still make sense and I don't think calling another repository in a repository would be a good practice?

4
  • Thanks its been buggying me for some time now. Since I find the ones I seen in the book are too simple they dont' show you what to do in these situations.
    – chobo2
    Sep 30, 2009 at 0:18
  • I'm basically doing the same as you and yeah if I have a linq2sql class that's used in more than 1 repository and I need to change the table structure I break DRY. Less than ideal. I now plan it a little better so I don't need to use a linq2sql class more than once which I guess is good seperation of concerns but I foresee a day when this is going to be a real issue for me.
    – griegs
    Sep 30, 2009 at 0:25
  • I asked a similar question (but not identical) here: stackoverflow.com/questions/910156/…
    – Grokys
    Sep 30, 2009 at 0:30
  • Ya but it seems hard to plan it for all situations. Like I said I can merge maybe the login and registration into an Authentication and have 2 separate layers. That probably will solve my problem. But what happens if in say the profile page of my site I want to show them their key for whatever reason(maybe I will let htem change it or something). Now what do I do break DRY and write the same thing? Or try to make a repository that can somehow fit all 3 of these tables in with a good name.
    – chobo2
    Sep 30, 2009 at 0:31

7 Answers 7

41

One thing that I did wrong when playing around with repository pattern—just like you, I thought that table relates to repository 1:1. When we apply some rules from domain-driven design, the grouping repositories problem often disappears.

The repository should be per the Aggregate root and not table. It means, if entity shouldn't live alone (i.e., if you have a Registrant that participates in a particular Registration), it's just an entity, and it doesn't need a repository. It should be updated/created/retrieved through the repository of aggregate root it belongs to.

Of course, in many cases, this technique of reducing the count of repositories (actually, it's more a technique to structure your domain model) can't be applied, because every entity is supposed to be an aggregate root (that highly depends on your domain, I can provide blind guesses only). In your example, License seems to be an aggregate root, because you need to be able to check them without any context of the Registration entity.

But that does not restrict us to cascade repositories (the Registration repository is allowed to reference the License repository if needed). That does not restrict us to reference the License repository (preferable, through IoC) directly from the Registration object.

Just try not to drive your design through complications provided by technologies or misunderstanding something. Grouping repositories in ServiceX just because you don't want to construct two repositories isn’t good idea.

Much better would be to give it a proper, name, RegistrationService, for example.

But services should be avoided in general. They often are cause that leads to an anemic domain model.

Do start to use IoC. It truly eases the pain of injecting dependencies.

Instead of writing:

var registrationService = new RegistrationService(new RegistrationRepository(),
      new LicenseRepository(), new GodOnlyKnowsWhatElseThatServiceNeeds());

you will be able to write:

var registrationService = IoC.Resolve<IRegistrationService>();

P.S.: It would be better to use so called common service locator, but that's just an example.

12
  • 18
    Hahaha... I'm giving advice to use service locator. Always joy to see how dumb I've been in past. Oct 25, 2010 at 22:22
  • 1
    @Arnis It sounds as if your opinions have changed -- I'm interested how would you answer this question differently now?
    – ngm
    Apr 14, 2011 at 11:12
  • 11
    @ngm a lot have changed since I answered this. I still agree that aggregate root should draw transactional boundaries (be saved as a whole), but I'm much less optimistic about abstracting persistence using repository pattern. Lately - I'm just using ORM directly, because things like eager/lazy loading management are too awkward. It's much more beneficial to focus on developing rich domain model instead of focusing on abstracting persistence. Apr 14, 2011 at 15:08
  • 2
    @Developer no, not exactly. they still should be persistence ignorant. you retrieve aggregate root from outside and call method on it that does the job. my domain model has zero references, just standard .net framework ones. to achieve that, You must have rich domain model and tools that are smart enough (NHibernate does the trick). May 24, 2011 at 9:11
  • 1
    On the contrary. Fetching more than one ggregate often means that you can use the PK or indexes. Much faster than taking advantage of the relations that EF generates. The smaller root aggregates, the easier to get performance on them.
    – jgauffin
    May 21, 2013 at 12:38
5

One thing I've started doing to address this is to actually develop services that wrap N repositories. Hopefully your DI or IoC frameworks can help to make that easier.

public class ServiceImpl {
    public ServiceImpl(IRepo1 repo1, IRepo2 repo2...) { }
}

Does that make sense? Also, I understand that speaking of services in this manor may or may not actually comply with DDD principles, I just do it because it seems to work.

7
  • 1
    Nopethat does not make much sense. I don't use DI or IoC frameworks at this current time because I got enough on my plate as it is.
    – chobo2
    Sep 30, 2009 at 1:19
  • 1
    If you can instantiate your repos w/ just a new(), you could try this... public ServiceImpl() : this(new Repo1, new Repo2...) {} as an additional constructor in the service.
    – neouser99
    Sep 30, 2009 at 14:53
  • Dependency injection? I do that already but still not sure what your code is dong and what it solves.
    – chobo2
    Sep 30, 2009 at 17:26
  • I'm specifically going after the merging of repositories. Which code does not make sense? If you are using DI, then the code in the answer will work in the sense that your DI framework will inject those IRepo services, in the comment code it's basically just a small work around to do DI (basically your no parameter constructor 'injects' those dependencies into your ServiceImpl).
    – neouser99
    Sep 30, 2009 at 18:26
  • I use DI already so I can unit test better. My problem is that if you make your service layers and repos with to detailed of names. Then if you ever need to use them anywhere else it will look weird calling like the RegistrationService Layer that Calls the RegRepo in some other class say like the ProfileClass. So I am not seeing from you example what your fully doing. Like If you start to have too many Repos in the same service layer your going to have so much different bussiness logic and validation logic. Since in the service layer you usually put in validation logic. So many I need more...
    – chobo2
    Oct 1, 2009 at 4:56
2

I have an abstract base class defined as follows:

public abstract class ReadOnlyRepository<T,V>
{
     V Find(T lookupKey);
}

public abstract class InsertRepository<T>
{
     void Add(T entityToSave);
}

public abstract class UpdateRepository<T,V>
{
     V Update(T entityToUpdate);
}

public abstract class DeleteRepository<T>
{
     void Delete(T entityToDelete);
}

You can then derive you repository from the abstract base class and extend your single repository as long at the generic arguments differ for example;

public class RegistrationRepository: ReadOnlyRepository<int, IRegistrationItem>,
                                     ReadOnlyRepository<string, IRegistrationItem> 

etc....

I need the separate repositories because we do have restrictions on some of our repositories and this gives us maximum flexibility.

3
  • So your trying to make a generic repository to deal with this all?
    – chobo2
    Sep 30, 2009 at 3:49
  • So what actually goes into say the Update method. Like you have like this V update and it pass in a T entitytoUpdate but there is no code actually updating it or is there?
    – chobo2
    Sep 30, 2009 at 17:32
  • Yes.. There will be code in the update method because you will write a class that descends from the generic repository. The implementation code can be Linq2SQL or ADO.NET or whatever you have chosen as your data access implementation technology Sep 30, 2009 at 23:13
2

I have this as my repository class and yeah I extend in the table / area repository, but still I sometimes have to break DRY.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MvcRepository
{
    public class Repository<T> : IRepository<T> where T : class
    {
        protected System.Data.Linq.DataContext _dataContextFactory;

        public IQueryable<T> All()
        {
            return GetTable.AsQueryable();
        }

        public IQueryable<T> FindAll(Func<T, bool> exp)
        {
            return GetTable.Where<T>(exp).AsQueryable();
        }

        public T Single(Func<T, bool> exp)
        {
            return GetTable.Single(exp);
        }

        public virtual void MarkForDeletion(T entity)
        {
            _dataContextFactory.GetTable<T>().DeleteOnSubmit(entity);
        }

        public virtual T CreateInstance()
        {
            T entity = Activator.CreateInstance<T>();
            GetTable.InsertOnSubmit(entity);
            return entity;
        }

        public void SaveAll()
        {
            _dataContextFactory.SubmitChanges();
        }

        public Repository(System.Data.Linq.DataContext dataContextFactory)
        {
            _dataContextFactory = dataContextFactory;
        }

        public System.Data.Linq.Table<T> GetTable
        {
            get { return _dataContextFactory.GetTable<T>(); }
        }

    }
}

Or better:

public class AdminRepository<T> : Repository<T> where T: class
{
    static AdminDataContext dc = new AdminDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["MY_ConnectionString"].ConnectionString);

    public AdminRepository()
        : base( dc )
    {
    }

I also have a datacontext which was created using Linq2SQL.dbml class.

So now I have a standard repository implementing standard calls like All and Find and in my AdminRepository I have specific calls.

It doesn't answer the question of DRY though, I don't think.

2
  • What " Repository" for? and like CreateInstance? Not sure what everything you have is doing.
    – chobo2
    Sep 30, 2009 at 3:49
  • It's generic as anything. Basically you need to have a specific repository for your (area). Check out the edit above for my AdminRepository.
    – griegs
    Sep 30, 2009 at 5:42
1

Here is an example of a generic Repository implementation using FluentNHibernate. It is capable of persisting any class that you have written a mapper for. It is even capable of generating your database based off of the mapper classes.

0

I suggest you to look at Sharp Architecture. They suggest using one repository per entity. I'm using it currently in my project and am very pleased with results.

2
  • I would give a +1 here, but he has indicated that DI or IoC containers are not quite an option (granted those aren't the only benefits of Sharp Arch). I'm guessing there is some to a lot of existing code the he is working around.
    – neouser99
    Sep 30, 2009 at 14:56
  • What is considered a entity? Is that the entire database? or is that a database table? DI or IoC containers are not a option at this time since I just don't want to learn that ontop of the other 10 things I am learning at the same time. they are something I will look into my next revision of my site or my next project. Even though I am not sure if it will be this one a quick look at the site and it seems to want you to use nhirbrate and I am using to linq to sql at this current time.
    – chobo2
    Sep 30, 2009 at 17:30
0

The Repository pattern is a bad design pattern. I work with many old .NET projects and this pattern typically causes "Distributed Transactions", "Partial Rollback" and "Connection Pool Exhausted" errors which could be avoided.

The problem is that the pattern tries to handle connections and transactions internally but those should be handled at the Controller layer. Also Entity Framework already abstracts a lot of the logic.

I would suggest using the Service pattern instead to reuse shared code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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