5

I have implemented domain events as prescribed in Udi Dahan's Domain Events - Salvation article.

As far as I understand, domain events can be run asynchronously to the thread from which it was raised (typically from a domain model or service).

There does not need to be any sort of "shared" unit of work or repository implementation and no transactional consistency is required.

Question: Why has Udi not implemented the handling of domain events in a separate thread?

For example, I have added the creation of a Task to handle events asynchronously:

public static void Raise<T>(T domainEvent) where T : IDomainEvent
{
    if (Container != null)
    {
        foreach (var handler in Container.ResolveAll<IDomainEventHandler<T>>())
        {
            Task.Factory.StartNew(() => 
            { 
                handler.Handle(domainEvent); 
            }).ContinueWith(t => {
                // Log exception
            }, TaskContinuationOptions.OnlyOnFaulted);
        }
    }
}

Are there any multithreading issues that could arise from this?

EDIT: Note that while these domain events would be light-weight, they will still be running on IIS as this is a MVC web project.

Dave New
  • 38,496
  • 59
  • 215
  • 394
  • 1
    What's problematic in your implementation is that you won't notice when one of the handlers fails. So to do this reliably its best to place domain events in sort of queue or table and let a background process pick them up. Or at least log a failure in such way that you can reexecute the handler for a certain domain event. – Steven Apr 03 '14 at 10:10
  • @Steven: Apologies, I have included such handling now. My question is more around thread-safety. – Dave New Apr 03 '14 at 10:56
  • 3
    About your question "Why has Udi not implemented the handling of domain events in a separate thread", it's of course only something that Udi can answer, but I think it's all about YAGNI. If you don't need it, don't do it. Processing stuff in the background is harder to test, harder to get right; its easier to get bugs. – Steven Apr 03 '14 at 11:05
  • 3
    Also note that there's no guarantee that all handlers even run, because IIS will kill background threads aggressively if the AppDomain is recycled. This means that any operation in the queue will get lost. – Steven Apr 03 '14 at 11:06

0 Answers0