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.
This is very valid, and in fact very similar to the setup we have.
However in your question, you’ve got
IRepositoryin 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?