How to use the repository pattern correctly?

C#.Netasp.netasp.net MvcRepository Pattern

C# Problem Overview


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 4 tables I need to update and before I had 3 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 merege these 2 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 2 service layers going to the same repository since I think having all the logic for 2 different parts of a site would be long and I would have to have names like ValidateLogin(), ValdiateRegistrationForm(),ValdiateLoginRetrievePassword() and etc.

Or call the Repository anyways 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?

C# Solutions


Solution 1 - C#

One thing that i did wrong when played 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 - grouping repositories problem often disappears.

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

Of course - in many cases, this technique of reducing 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 with no context of Registration entity.

But that does not restrict us to cascade repositories (Registration repository is allowed to reference License repository if needed). That does not restrict us to reference License repository (preferable - through IoC) directly from 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 2 repositories ain't good idea.

Much better would be to give it a proper name - RegistrationService i.e.

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

EDIT:
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. Would be better to use so called common service locator but that's just an example.

Solution 2 - C#

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.

Solution 3 - C#

What I am doing is I have a 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. Hope this helps.

Solution 4 - C#

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>(); }
        }

    }
}

EDIT

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.

Doesn't answer the question of DRY though I don't think.

Solution 5 - C#

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.

Solution 6 - C#

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

Solution 7 - C#

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 EntityFramework already abstracts a lot of the logic. I would suggest using the Service pattern instead to reuse shared code.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionchobo2View Question on Stackoverflow
Solution 1 - C#Arnis LapsaView Answer on Stackoverflow
Solution 2 - C#neouser99View Answer on Stackoverflow
Solution 3 - C#Michael MannView Answer on Stackoverflow
Solution 4 - C#griegsView Answer on Stackoverflow
Solution 5 - C#James JonesView Answer on Stackoverflow
Solution 6 - C#SlyView Answer on Stackoverflow
Solution 7 - C#ColacXView Answer on Stackoverflow