Domain Events in Domain Driven Design

This demo is about creating domain events using Ninject with a sample console application. The demonstration is to mimic a Checkout from an eCommerce Application. Where in the action performed is CustomerCheckOut which is handled by CustomerCheckOutHandler class.

Step 1: Create an empty interface IDomainEvent

public class CustomerCheckOut : IDomainEvent
{
    public String CustomerName { get; set; }
}

Step 2: Create a class CustomerCheckOut and implement interface IDomainEvent

public class CustomerCheckOut : IDomainEvent
{
    public String CustomerName { get; set; }
}

Step 3: Create DomainHandler interface

public interface IDomainHandler<in T> where T : IDomainEvent
    {
        void Handle(T @event);
    }

Step 4: Create CustomerCheckOutHandle class

public class CustomerCheckOutHandle : IDomainHandler<CustomerCheckOut>
{
    public void Handle(CustomerCheckOut @event)
    {
        Console.WriteLine(@event.CustomerName); 
    }
}

Step 5: Add following Classes with Ninject reference added to the project

public static class DomainEvent
{
    public static IEventDispatcher Dispatcher { get; set; }

    public static void Raise<T>(T @event) where T : IDomainEvent
    {
        Dispatcher.Dispatch(@event);
    }

}

public class NinjectEventContainer : IEventDispatcher
{
    private readonly IKernel _kernel;

    public NinjectEventContainer(IKernel kernel)
    {
        _kernel = kernel;
    }

    public void Dispatch<TEvent>(TEvent eventToDispatch) where TEvent : IDomainEvent
    {
        foreach (var handler in _kernel.GetAll<IDomainHandler<TEvent>>())
        {
            handler.Handle(eventToDispatch);
        }
    }
}

public interface IEventDispatcher
{
    void Dispatch<TEvent>(TEvent eventToDispatch) where TEvent : IDomainEvent;
}

Now the Final piece of code that maps CustomerCheckOut to its handler

StandardKernel kernel = new StandardKernel();
DomainEvent.Dispatcher = new NinjectEventContainer(kernel);
kernel.Bind<IDomainHandler<CustomerCheckOut>>().To<CustomerCheckOutHandle>();

And finally one can raise the events by invoking the Raise Event like this:

DomainEvent.Raise(new CustomerCheckOut() { CustomerName = "Hozefa Mangalorewala" });

Let me know if this is useful,

Happy Coding ...