I know there is a lot of similar information online and also on stackoverflow, but I'm still not sure where to put the logic of persistence into my project. I don't yet use any ORM, IoC and UnitOfWork concepts (too much new stuff for a beginner in the ddd world).
I see two options for my Order model:
Order
class and an IOrderRepository
interface. Order
class has a private instance of the IOrderRepository
which is passed in the constructor. Order class has a public Insert
method, which calls the IOrderRepository.Insert
method. The actual implementetion of the repository is in OrderRepository
class of the Infrastructure layer. The Service layer would contain an OrderService
class which instantiates my model with the appropriate repository and then calls Order.Insert()
. The bad: we have to inject an interface (or multiple instances) of the repository to the model class, persistence logic is inside the model. The good: sometimes something has to be done before or after the insert method is called and this could nicely fit into the Insert
method of the Order
class, for example raising domain events or whatever.Model
assembly there is only Order
class. The Service layer creates new Order
and new OrderRepository
and executes orderRepository.Insert(order)
.Could you please explain which concept is better in simple words (explain like I'm Five).
Your domain classes should be focused on business logic of domain only, and they should be persistent ignorant (i.e. persistence should be separated from business logic). Adding persistence-related operations violates Single Responsibility Principle. Also dependency on repository makes your domain classes complex, instead of being simple POCO entities.
Let's think about this design from coding point. You have to provide repository instance to each Order
, and then call order.Insert()
for this order to pass itself to repository which you have injected into order. Sounds complicated. Much simpler will be use repository.Save(order)
. Sometimes it's OK to have CRUD methods on class (see Active Record pattern). But this approach is good when you don't have complex domain model.
I think best place for persistence of your domain is application services (maybe you call this layer as Service layer). They load entities from repositories, perform operations (it could be simple operations on entities, or calls to domain services), and then state of domain gets saved.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments