Where to raise persistence-dependent domain events - service, repository, or UI?

前端 未结 6 1835
暖寄归人
暖寄归人 2021-01-31 09:03

My ASP.NET MVC3 / NHibernate application has a requirement to fire off and handle a variety of events related to my domain objects. For example, an Order object mig

6条回答
  •  长情又很酷
    2021-01-31 09:21

    I think, you shouold have a Domain Service, as David Glenn said.

    The problem I ran into was that the service layer would end up having to pull a copy of some objects prior to saving the modified version to compare the new one against the old one and then decide what events should be fired.

    Your Domain Service should contains methods that clearly state what you want to do with your domain Entity, like: RegisterNewOrder, CreateNoteForOrder, ChangeOrderStatus etc.

    public class OrderDomainService()
    {
        public void ChangeOrderStatus(Order order, OrderStatus status)
        {
            try
            {
                order.ChangeStatus(status);
                using(IUnitOfWork unitOfWork = unitOfWorkFactory.Get())
                {
                    IOrderRepository repository = unitOfWork.GetRepository();
                    repository.Save(order);
                    unitOfWork.Commit();
                }
                DomainEvents.Publish(new OrderStatusChangedEvent(order, status));
            }
    
        }
    }
    

提交回复
热议问题