Posts Tagged ‘command handlers’

How to NOT inject services into entities (copycat title)

January 17, 2011

Working on my hobby poject I came across a familiar situation of having to interact with a (to my domain) external service. The service in this case is push notification. I know the “official” guidance is to not inject services (or anything else for that matter) into domain entities (I completely agree), but I was struggeling with how to follow this advice without breaking the incapsulation of my domain. The critical advice came from a blog post (http://thinkbeforecoding.com/post/2009/03/04/How-not-to-inject-services-in-entities – see “Behavior methods”) by Jérémie Chassaing.

The techniques is familiar, but i’m surprised how perfectly in makes sence for these kinds of cases. My event handler ended up looking like this (domain has been substituted for a basic blog for the example):

public class PostChangeHandler : IHandle<PostAddedEvent>, IHandle<PostUpdatedEvent>
{
     ISessionFactory sessionFactory;
     ISubscriberNotificationService subscriberNotificationService;

     public PostChangeHandler(ISessionFactory sessionFactory, ISubscriberNotificationService subscriberNotificationService)
     {
         this.sessionFactory = sessionFactory;
         this.subscriberNotificationService = subscriberNotificationService;
     }

     void IHandle<CommentAddedEvent>.Handle(CommentAddedEvent domainEvent)
     {
         NotifySubscribers(domainEvent.PostId);
     }

     void IHandle<CommentUpdatedEvent>.Handle(CommentUpdatedEvent domainEvent)
     {
         NotifySubscribers(domainEvent.PostId);
     }

     private void NotifySubscribers(Guid postId)
     {
         using (var s = sessionFactory.OpenSession())
         using (var tx = s.BeginTransaction())
         {
             var post = s.Get<Post>(postId);
             post.NotifySubscribers(subscriberNotificationService);

             tx.Commit();
         }
     }
 }

Command handlers are a great candidate for DI in my opinion. Leaving it up to the command/event handler to supply the service to use in the concrete case makes a lot of sense too. I find that the above leaves me with a domain that describes exactly what i want it to: “Who should be notified?” – all while abstracting away the concrete “How”.

Advertisements