0

I am reading a book about domain driven design. There is a chapter about Domain Events. The author indicates that there is a reason for concern if you use a callback collection with [ThreadStatic] attribute in ASP.Net application and references to this blog article: http://www.hanselman.com/blog/ATaleOfTwoTechniquesTheThreadStaticAttributeAndSystemWebHttpContextCurrentItems.aspx

I read the explanation on this blog. But i dont understand exactly what the concern is. Does anybody use this domain event approach and can share his experience ?

Here is the code for domain event class (it is from Udi Dahan):

 public static class DomainEvents
    {
        [ThreadStatic]
        private static List<Delegate> _actions;
        private static List<Delegate> Actions
        {
            get
            {
                if (_actions == null)
                {
                    _actions = new List<Delegate>();
                }
                return _actions;
            }
        }

        public static IDisposable Register<T>(Action<T> callback)
        {           
            Actions.Add(callback);

            return new DomainEventRegistrationRemover(() => Actions.Remove(callback));
        }

        public static void Raise<T>(T eventArgs)
        {
            foreach (Delegate action in Actions)
            {
                Action<T> typedAction = action as Action<T>;
                if (typedAction != null)
                {
                    typedAction(eventArgs);
                }
            }
        }

        private sealed class DomainEventRegistrationRemover : IDisposable
        {
            private readonly Action _callOnDispose;

            public DomainEventRegistrationRemover(Action toCall)
            {
                _callOnDispose = toCall;
            }

            public void Dispose()
            {
                _callOnDispose();
            }
        }
    }
Lahmacun
  • 97
  • 1
  • 8

1 Answers1

0

Here is a related question:

ThreadStaticAttribute in ASP.NET

I have moved away from this type of static implementation for domain events and prefer that the domain returns the event from the command method. I find it easier to work with and reason about. Here is another related question:

Is it safe to publish Domain Event before persisting the Aggregate?

Eben Roux
  • 12,983
  • 2
  • 27
  • 48