views:

138

answers:

3

I am trying to use Domain Driven Development (DDD) for my new ASP.NET MVC2 project with Entity Framework 4. After doing some research I came up with the following layer conventions with each layer in its own class project:

MyCompany.Domain

     public class User
    {
        //Contains all the properties for the user entity
    }

    public interface IRepository<T> where T : class
    {
        IQueryable<T> GetQuery();
        IQueryable<T> GetAll();
        IQueryable<T> Find(Func<T, bool> condition);
        T Single(Func<T, bool> condition);
        T First(Func<T, bool> condition);
        T GetByID(int id);
        void Delete(T entity);
        void Add(T entity);
        void Attach(T entity);
        void SaveChanges();
    }

  public interface IUserRepository: IRepository<User> {}

    public class UserService
    {
        private IUserRepository _userRepository;
        public UserService(IUserRepository userRepository)
        {
            _userRepository = userRepository;
        }
    // This class will hold all the methods related to the User entity
    }

MyCompany.Repositories

public class UserRepository : IRepository<User>
{
    // Repository interface implementations
}

MyCompany.Web --> This is the MVC2 Project

Currently my Repositories layer holds a reference to the Domain layer. From my understanding injecting a UserRepository to the UserService class works very well with unit testing as we can pass in fake user repositories. So with this architecture it looks like my Web project needs to have a references to both my Domain and Repositories layers. But is this a valid? Because historically the presentation layer only had a reference to the Business Logic layer.

+5  A: 

This is very valid, and in fact very similar to the setup we have.

However in your question, you've got IRepository in the domain project, i would put this in your Repositories assembly.

Your Domain layer should have your domain entities and business logic. Your Repository layer should have the generic repository interface, and concrete implementations of this, one for each aggregate root.

We also have a Service layer mediating between the UI (Controllers) and the Repository. This allows a central location to put logic which does not belong in the Repository - things like Paging and Validation.

This way, the UI does not reference the Repository, only the Service Layer.

We also use DI to inject the EntityFrameworkRepository into our Service Layer, and a MockRepository into our test project.

You seem to be on the right track, but since it seems to want to go "DDD-All-The-Way", have you considered implementing the Unit of Work pattern to manage multiple repositories sharing the same context?

RPM1984
Thanks for the response. I would definitely like to use the Unit Of Work pattern. Can you please provide me with a brief implementation of this pattern?
Kumar
In short, with EF, it's implemented as a wrapper for the datacontext, which is passed through the ctor for the Repositories. So, you create a new Uow (which creates a new DC), then pass this to each repository (preferably with a DI container). You then "Commit" on the UoW which is the equivalent of "SaveChanges" on the ctx, but it will SaveChanges across all repositories you work with. There's a great MSDN Blog on EF/Repository/UoW here - http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx. HTH
RPM1984
Posted some comments as an answer.
Arnis L.
+4  A: 

Just some notes on @RPM1984 answer...

However in your question, you've got IRepository in the domain project, i would put this in your Repositories assembly.

While it does not matter that much where You put things physically, it's important to remember that abstractions of repositories are part of domain.

We also have a Service layer mediating between the UI (Controllers) and the Repository. This allows a central location to put logic which does not belong in the Repository - things like Paging and Validation.

I believe that it's not good idea to create service just for paging and validation. Even worse if it's created artificially - just because 'everything goes through services' and 'that way You don't need to reference repositories from UI'. Application services should be avoided when possible.

For input validation - there's already nice point for that out of the box. If You use asp.net mvc, consider following MVVM pattern and framework will provide good enough ways to validate Your input view models.

If You need interaction across multiple aggregate roots (which is a sign that You might be missing new aggregate root) - write domain service.

You seem to be on the right track, but since it seems to want to go "DDD-All-The-Way", have you considered implementing the Unit of Work pattern to manage multiple repositories sharing the same context?

I think unit of work should be avoided too. Here's why:

Another example, UoW is really a infrastructure concern why would you bring that into the domain?. If you have your aggregate boundaries right, you don’t need a unit of work.


Repositories do not belong in the domain. Repositories are about persistence (ie infrastructure), domains are about business.

Repositories got kind a mixed responsibility. From one side - business don't care how and where it will persist data. From other - knowledge that customers can be found by their shopping cart content is (oversimplified example). Hence - I'm arguing that only abstractions should be part of domain. Additionally - I'm against direct usage of repositories from domain model cause it should be persistence ignorant.

Service Layer allows a central point for 'business validation'.

Application services basically are just facades. And every facade is bad if complexity it adds overweights problems it solves.

Here's a bad facade:

public int incrementInteger(int val){
  return val++;
}

Application services must not contain business rules. That's the point of domain driven design - ubiquitous language and isolated code that reflects business as clear and simply as possible.

MVC is good for simple validation, but not for complex business rules (think specification pattern).

And that's what it should be used for. E.g. - to check if posted value can be parsed as datetime which is supposed to be passed as argument to domain. I call it UI validation. There are many of them.

RE UoW - im intrugued by that sentence, but can you elaborate? UoW IS indeed an insfrastructure concern, but again this is in my repositories/data tier, not my domain. All my domain has is business objects/specifications.

Unit of work pattern encourages us to loosen aggregate root boundaries. Basically - it allows us to run transactions over multiple roots. Despite that it sits outside domain, it still does implicit impact on domain and modeling decisions we make. Often enough it leads back to so called anemic domain model.

One more thing: layers != tiers.


The other point i'd make is DDD is a guideline, not a be-all-and-end-all.

Yeah, but that shouldn't be used as an excuse. :)

The other reason for our service layer is that we have an Web API. We do NOT want our Web API calling into our repositories, we want a nice fluent interface for which both the Web App and API can call through.

If there's nothing more than retrieving root and calling it's method - service just to wrap that is not necessary. Therefore - I suspect that Your real issue is lack of this isolation, hence - there's need to orchestrate interaction between roots.

Here You can see some details of my current approach.

Another BIG reason for our service layer, is our Repositories return IQueryable, so they have no logic whatsoever. Our Service Layer projects the linq expressions, into concretes

That does not sound right. The same problem - lack of isolation.

In this case - repositories do not abstract persistence enough. They should have logic - one which is persistence related. Knowledge how to store and retrieve data. Delegating that "somewhere outside" ruins whole point of repositories and all what will be left - an extension point to mock out data access for testing (which ain't bad thing).

Another thing - if repositories return raw IQueryable, that automatically ties service layer with unknown (!) LINQ provider.

And less bad thing (You might not even need that) - because of high coupling, it might be quite hard to switch persistence to another technology.

Don't forget that we are talking about technical concerns. These things got nothing to do with design itself, they just make it possible.


If you don't use a service layer, how would you (for example) retrieve a list of orders for a product? You would need a method in your Repository called "GetOrdersForProduct" - which i do not think is good design. Your Repository interface becomes huge, impossible to maintain. We use a very generic Repository (Find, Add, Remove, etc). These methods work off the object set in our model. The versatility/querying power is brought forward to the service layer

This one is tricky. I'll just leave good reference.

With unknown provider i mean - You can't really now what's underneath from service layer. It might be Linq to objects, it might be Linq to xml, Linq to sql, NHIbernate.Linq and bunch of other provider implementations. Bad thing is - You can't know what's supported.

This will run just fine if it's Linq to objects and will fail if it needs to be translated to sql:

customers.Where(c=>{var pickItUp=c.IsWhatever; return pickItUp;});
Arnis L.
I have never seen anyone with such different opinions to me, quite interesting. Too many things we could argue/disagree on, so i don't even know where to start. :) Good to see different opinions though.
RPM1984
@RPM1984 that's just my current understanding. as usual - there's no <strike>spoon</strike> silver bullet.
Arnis L.
Couple of points though (i can't resist). Again these are just my opinions. Repositories do not belong in the domain. Repositories are about persistence (ie infrastructure), domains are about business. Service Layer allows a central point for 'business validation'. MVC is good for simple validation, but not for complex business rules (think specification pattern). RE UoW - im intrugued by that sentence, but can you elaborate? UoW IS indeed an insfrastructure concern, but again this is in my repositories/data tier, not my domain. All my domain has is business objects/specifications. Thats it.
RPM1984
@RPM1984 check answer for response. :)
Arnis L.
Yeah, I'm in @RPM1984's camp domain == business layer.
kenny
@kenny emmm... did I say anything contradictory to that?
Arnis L.
@Arnis L - very good update (+1). Seems like you've been reading a lot of DDD articles/books - buzzwords thrown everywhere. :) The other point i'd make is DDD is a guideline, not a be-all-and-end-all. The other reason for our service layer is that we have an Web API. We do NOT want our Web API calling into our repositories, we want a nice fluent interface for which both the Web App and API can call through. Another BIG reason for our service layer, is our Repositories return IQueryable, so they have no logic whatsoever. Our Service Layer projects the linq expressions, into concretes.
RPM1984
Man i could talk design patterns all day, love it. :)
RPM1984
@Arnis L - another final point on the service layer. If you don't use a service layer, how would you (for example) retrieve a list of orders for a product? You would need a method in your Repository called "GetOrdersForProduct" - which i do not think is good design. Your Repository interface becomes huge, impossible to maintain. We use a very generic Repository (Find, Add, Remove, etc). These methods work off the object set in our model. The versatility/querying power is brought forward to the service layer.
RPM1984
@RPM1984 and some more comments... :P
Arnis L.
IQueryable vs concrete is a technical concern, nothing to do with DDD. This is my point of DDD being a guideline. Personally i would hate to see your Repository with 100 methods for retrieving custom information. If you switch from NHibernate to Entity Framework, why should all your methods be also changed? For me to change, all i need to do is create another concrete Repository, the methods for retrieving customers do not change. IQueryable is LINQ-Objects - making it very versatile in this sense (it is never 'unknown'). My repositories do have persistence logic, but nothing else.
RPM1984
Let's agree to disagree - we need to stop, otherwise we will cause a 'stack-overflow' on this answer. :)
RPM1984
@RPM1984 agreeing is not what's important for me here. I'm learning through teaching. will do "one more round" a bit later. :)
Arnis L.
Come on mate, let it go. :)
RPM1984
@RPM1984 as You wish
Arnis L.
@Arnis L - i love chatting design, but i'd rather leave this question alone. Maybe we should start a new question (actually a CWiki), asking what difference ways people implement DDD in .NET applications? What are the pros/cons of each, what are limitations, etc. Would be interesting.
RPM1984
@RPM1984 actually, I do think that this form of discussion is more efficient. + there's high probability that such a generic question would be closed. You might want to check out yahoo group dedicated to DDD: http://bit.ly/cQMOz
Arnis L.
A: 

You may want to explore the way the Sharp Architecture framework is tackling this problem, as it looks like you're basically re-implementing the same ideas. The Northwind application tutorial has some nice discussion on these concepts.

Visionary Software Solutions