Services and Repositories in DDD (C#)

Gup3rSuR4c picture Gup3rSuR4c · Nov 11, 2010 · Viewed 14.1k times · Source

How do Services and Repositories relate to each other in DDD? I mean, I've been reading up on DDD for the past 2 days and everywhere I go, there's always a Service layer and there's always a Repository layer. How do these differentiate or compliment each other?

From what I've read, isn't the Repository the layer responsible for delegating interactions between the application and the data?

So, what's the need for the Service layer if it has to implement the Repository to interact with the data anyway even though the Repository probably already implements the methods needed to do so?

I'd appreciate some enlightenment on the subject.

P.S. Don't know if this will help any, but I'm working with an ASP.NET MVC 2 application in which I'm trying to implement the Repository pattern. I just finished implementing the Dependency Injection pattern (for the first time ever)...

UPDATE

Okay, with so many answers, I think I understand what the difference is. So, to review (correct me if I'm wrong):

  • A Repository layer interacts only with a single object out of the database or the ORM, IEmployeeRepository -> Employee.

  • A Service layer encapsulates more complex functionality on objects returned from Repositories, either one or multiple.

So, then I have a sub question. Is it considered bad practice to create abstract objects to be sent to my views? For example an AEmployee (A for abstract because to me I means interface) which contains properties from Employee and X or X?

Actually, one more subquestion. If a Service layer can be considered "tuned" for an application does it need to be implemented with an interface?

Answer

quentin-starin picture quentin-starin · Nov 11, 2010

The Service will use a Repository to retrieve an Entity and then call methods on it (the Entity) to perform the Command/task.