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

前端 未结 6 1825
暖寄归人
暖寄归人 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:26

    My solution is that you raise events in both Domain layer and service layer.

    Your domain:

    public class Order
    {
        public void ChangeStatus(OrderStatus status)
        {
            // change status
            this.Status = status;
            DomainEvent.Raise(new OrderStatusChanged { OrderId = Id, Status = status });
        }
    
        public void AddNote(string note)
        {
            // add note
            this.Notes.Add(note)
            DomainEvent.Raise(new NoteCreatedForOrder { OrderId = Id, Note = note });
        }
    }
    

    Your service:

    public class OrderService
    {
        public void SubmitOrder(int orderId, OrderStatus status, string note)
        {
            OrderStatusChanged orderStatusChanged = null;
            NoteCreatedForOrder noteCreatedForOrder = null;
    
            DomainEvent.Register(x => orderStatusChanged = x);
            DomainEvent.Register(x => noteCreatedForOrder = x);
    
            using (var uow = UnitOfWork.Start())
            {
                var order = orderRepository.Load(orderId);
                order.ChangeStatus(status);
                order.AddNote(note);
                uow.Commit(); // commit to persist order
            }
    
            if (orderStatusChanged != null)
            {
                // something like this
                serviceBus.Publish(orderStatusChanged);
            }
    
            if (noteCreatedForOrder!= null)
            {
                // something like this
                serviceBus.Publish(noteCreatedForOrder);
            }
        }
    }
    

提交回复
热议问题