简体   繁体   中英

DDD Architecture for ASP.NET MVC2 Project

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.

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. Eg - 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;});

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM