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

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

    It sounds like you need a Service Layer. A service Layer is another abstraction that sits between your front end or controllers and your business layer or domain model. It's kind of like an API into your application. Your controllers will then only have access to your Service Layer.

    It then becomes your service layer's responsibility to interact with your domain model

    public Order GetOrderById(int id) {
      //...
      var order = orderRepository.get(id);
      //...
      return order;
    }
    
    public CreateOrder(Order order) {
      //...
      orderRepositroy.Add(order);
      if (orderRepository.Submitchanges()) {
        var email = emailManager.CreateNewOrderEmail(order);
        email.Send();
      }
      //...
    }
    

    It's common to end up with 'manager' objects such as OrderManager to interact with orders and the service layer to deal with POCOs.

    Is it appropriate for the UI to raise these events? It knows what events have occurred and can fire them only after successfully having the service layer save the object. Something just seems wrong about having a controller firing off domain events.

    No. You will end up with problems if new actions are added and a developer is unaware or forgets that an email should be fired off.

    Should the repository fire off events after successfully persisting?

    No. the repository's responsability is to provide an abstraction over data access and nothing else

    Is there a better way to do this? Maybe having my domain objects queue up events which are fired by the service layer only after the object is persisted?

    Yes, it sounds like this should be handled by your service layer.

提交回复
热议问题