I have been pondering this for a while. In general I try to stay away from injecting services into my domain, but I have this case:
I have an PurchaseOrder object. This order is sent to a supplier using some service (Email or webservice). After the order is sent, a confirmation should be sent to the user that made the order.
So I realised this is a case where Domain Events would be a nice way of implementing this publishing an PurchaseOrderMade - event.
Then I came to think:
Is the order really made if the order wasnt sent?
You haven't made an order just because you decided to do it and wrote it down, but the order is made at the time when you have conveyed it to the supplier according to contract without errors.
So I redecided and thought that this might belong to the domain after all so I should send it by injecting a IPurchaseOrderSender to my domain and then publish an OrderMadeEvent after the successfull transaction and sending a confirmation in the EventHandler.
The reasoning is this:
- The sending of the order IS crucial part of the process and could cause state to alter (i.e. setting a flag that the order is sent)
- The confirmation is NOT crucial, should this fail the order is still made and everything would go as planned.
- It is easy to read, and to alter implementation of an IOrderService
The questions are:
- Is this really so bad to do?
- Does it break principles of DDD?
- Have you encountered this before and solved it in a better way?
Here is the code:
public void MakeOrder(PurchaseOrder order, IPurchaseOrderSender orderSender)
{
if(PurchaseOrders == null)
PurchaseOrders = new List<PurchaseOrder>();
PurchaseOrders.Add(order);
orderSender.Send(order);
DomainEvents.Raise(new PurchaseOrderIsMade(){Order = order});
}
public interface IPurchaseOrderSender
{
void Send(PurchaseOrder order);
}