Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real World ASP.NET MVC Repositories

In the real world, Controllers can potentially need to use data from a variety of database tables and other data stores. For example:

[Authorize]
    public class MembersController : Controller
    {
        ICourseRepository repCourse;
        IUserCourseRepository repUserCourse;
        IMember member;
        public MembersController(ICourseRepository repCourse, IUserCourseRepository repUserCourse, IMember member)
        {
            this.repCourse = repCourse;
            this.repUserCourse = repUserCourse;
            this.member = member;
        }

So:

  1. Should I use a repository for each table?

  2. I guess this is where the concept of agregates comes into play? Should I have one Repository per aggregate?

  3. Do I just add as many Repositories as I need to the constructor of the Controller?

  4. Is this a sign that my design is wrong?

NOTE:

The IMember interface essentially represents a helper object that puts a nice face on the Membership provider. Ie, it puts all the code in one place. For example:

        Guid userId;
        public Guid UserId
        {
            get
            {
                if (userId == null)
                {
                    try
                    {
                        userId = (Guid) Membership.GetUser().ProviderUserKey;
                    }
                    catch { }
                }
                return userId;
            }
        }

One problem with that is surely caching this kind of output. I can feel another question coming on.

EDIT:

I'm using Ninject for DI and am pretty sold on the whole DI, DDD and TDD thing. Well, sort of. I also try to be a pragmatist...

like image 425
awrigley Avatar asked Nov 24 '10 17:11

awrigley


1 Answers

1. Should I use a repository for each table?

Probably not. If you have a repository per table, you are essentially doing Active Record. I also personally prefer to avoid calling these classes "Repository" because of the confusion that can occur between Domain Driven Design's concept of a "Repository" and the class-per-table "Repository" that seems to have become commonly used with Linq2SQL, SubSonic, etc. and many MVC tutorials.

2. I guess this is where the concept of agregates comes into play? Should I have one Repository per aggregate?

Yes and yes. If you are going to go this route.

'3.' Do I just add as many Repositories as I need to the constructor of the Controller?

I don't let my controllers touch my repositories directly. And I don't let my Views touch my domain classes directly, either.

Instead, my controllers have Query classes that are responsible for returning View Models. The Query classes reference whatever repositories (or other sources of data) they need to compile the View Model.

like image 175
quentin-starin Avatar answered Oct 20 '22 01:10

quentin-starin