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?
In DDD, a repository is an objcect that participates in the domain but really abstracts away storage and infrastructure details. Most systems have a persistent storage like a database for its fully functioning. Applying repositories happens by integrating and synchronizing with existing aggregate objects in the system.
Repository layer is implemented to access the database and helps to extend the CRUD operations on the database. Whereas a service layer consists of the business logic of the application and may use the repository layer to implement certain logic involving the database.
The Service will use a Repository to retrieve an Entity and then call methods on it (the Entity) to perform the Command/task.
True, a repository works with data (ie. SQL, Webservice etc.) but that's the only job. CRUD operations, nothing more. There is no place for stored procedure based busines logic.
The service (or business logic layer) provides the functionality. How to fullfill a business request (ie. calculate salary), what you have to do.
Oh, and this is a really nice DDD book: http://www.infoq.com/minibooks/domain-driven-design-quickly
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With