Udi Dahan   Udi Dahan  –  The  Software  Simplist
 
Enterprise  Development  Expert  &  SOA  Specialist
 
 
Home Blog Consulting Training Articles Speaking About Contact
  

Domain Events - Take 2

Monday, August 25th, 2008.

My previous post on how to create fully encapsulated domain models introduced the concept of events as a core pattern of communication from the domain back to the service layer. In that post, I put up enough code to get the idea across but didn’t address issues like memory leaks and multi-threading. This post will show the solution to those two critical points.

I’ve snipped out one of the events in the previous example for brevity.

Previous API

The previous API looked like this:

   1:  public static class DomainEvents
   2:  {
   3:       public static event EventHandler GameReportedLost;
   4:       public static void RaiseGameReportedLostEvent()
   5:       {
   6:             if (GameReportedLost != null)
   7:                 GameReportedLost(null, null);
   8:       }
   9:   
  10:       public static event EventHandler CartIsFull;
  11:       public static void RaiseCartIsFull()
  12:       {
  13:             if (CartIsFull != null)
  14:                 CartIsFull(null, null);
  15:       }
  16:  }

One thing that we want to keep in the solution is that all the code to define events, their names, and the parameters they bring will be in one place - in this case, the DomainEvents class. One thing that we’d like to fix is the amount of code needed to define an event.

Previous Service Layer

Here’s what our previous service layer code looked like:

   1:  public class AddGameToCartMessageHandler :
   2:      BaseMessageHandler<AddGameToCartMessage>
   3:  {
   4:      public override void Handle(AddGameToCartMessage m)
   5:      {
   6:          using (ISession session = SessionFactory.OpenSession())
   7:          using (ITransaction tx = session.BeginTransaction())
   8:          {
   9:              ICart cart = session.Get<ICart>(m.CartId);
  10:              IGame g = session.Get<IGame>(m.GameId);
  11:   
  12:              Domain.DomainEvents.GameReportedLost +=
  13:                gameReportedLost;
  14:              Domain.DomainEvents.CartIsFull +=
  15:                cartIsFull;
  16:   
  17:              cart.Add(g);
  18:   
  19:              Domain.DomainEvents.GameReportedLost -=
  20:                gameReportedLost;
  21:              Domain.DomainEvents.CartIsFull -=
  22:                cartIsFull;
  23:   
  24:              tx.Commit();
  25:          }
  26:      }
  27:   
  28:      private EventHandler gameReportedLost = delegate { 
  29:            Bus.Return((int)ErrorCodes.GameReportedLost);
  30:          };
  31:   
  32:      private EventHandler cartIsFull = delegate { 
  33:            Bus.Return((int)ErrorCodes.CartIsFull);
  34:          };
  35:      }
  36:  }

Another thing that should be improved is the amount of code needed in the service layer.

Raising an event, though, should still be fairly simple - one line of code similar to DomainEvents.RaiseGameReportedLost().

New API

Here’s what the new API looks like:

   1:  public static class DomainEvents
   2:  {
   3:       public static readonly DomainEvent<IGame> GameReportedLost = 
   4:                                            new DomainEvent<IGame>;
   5:   
   6:       public static readonly DomainEvent<ICart> CartIsFull=
   7:                                            new DomainEvent<ICart>;
   8:  }

It looks like we’ve managed to bring down the complexity of defining an event.

Raising an event is slightly different, but still only one line of code (”this” refers to the Cart class that is calling this API): DomainEvents.CartIsFull.Raise(this);

New Service Layer

The advantage of having a disposable domain event allows us to use the “using” construct for cleanup.

   1:  public class AddGameToCartMessageHandler :
   2:      BaseMessageHandler<AddGameToCartMessage>
   3:  {
   4:      public override void Handle(AddGameToCartMessage m)
   5:      {
   6:          using (ISession session = SessionFactory.OpenSession())
   7:          using (ITransaction tx = session.BeginTransaction())
   8:          using (DomainEvents.GameReportedLost.Register(gameReportedLost))
   9:          using (DomainEvents.CartIsFull.Register(cartIsFull))
  10:          {
  11:              ICart cart = session.Get<ICart>(m.CartId);
  12:              IGame g = session.Get<IGame>(m.GameId);
  13:   
  14:              cart.Add(g);
  15:   
  16:              tx.Commit();
  17:          }
  18:      }
  19:   
  20:      private Action<IGame> gameReportedLost = delegate { 
  21:            Bus.Return((int)ErrorCodes.GameReportedLost);
  22:          };
  23:   
  24:      private Action<ICart> cartIsFull = delegate { 
  25:            Bus.Return((int)ErrorCodes.CartIsFull);
  26:          };
  27:      }
  28:  }

I also want to mention that you don’t necessarily have to have the same service layer object handle these events as that which calls the domain objects. In other words, we can have singleton objects handling these events for things like sending emails, notifying external systems, and auditing.

The Infrastructure

The infrastructure that makes all this possible (in a thread-safe way) is quite simple and made up of two parts, the DomainEvent that we saw being used above, and the DomainEventRegistrationRemover which handles the disposing:

   1:  using System;
   2:  using System.Collections.Generic;
   3:   
   4:  namespace DomainEventInfrastructure
   5:  {
   6:      public class DomainEvent<E> 
   7:      {
   8:          [ThreadStatic] 
   9:          private static List<Action<E>> _actions; 
  10:   
  11:          protected List<Action<E>> actions 
  12:          {
  13:              get { 
  14:                  if (_actions == null) 
  15:                      _actions = new List<Action<E>>(); 
  16:   
  17:                  return _actions; 
  18:              }
  19:          }
  20:   
  21:          public IDisposable Register(Action<E> callback) 
  22:          {
  23:              actions.Add(callback);
  24:              return new DomainEventRegistrationRemover(delegate
  25:                  {
  26:                      actions.Remove(callback);
  27:                  }
  28:              ); 
  29:          }
  30:   
  31:          public void Raise(E args) 
  32:          {
  33:              foreach (Action<E> action in actions) 
  34:                  action.Invoke(args);
  35:          }
  36:      }
  37:  }
  38:   

Note that the invocation list of the domain event is thread static, meaning that each thread gets its own copy - even though they’re all working with the same instance of the domain event.

Here’s the DomainEventRegistrationRemover - even simpler:

   1:  using System;
   2:   
   3:  namespace DomainEventInfrastructure
   4:  {
   5:      public class DomainEventRegistrationRemover : IDisposable 
   6:      {
   7:          private readonly Action CallOnDispose;
   8:   
   9:          public DomainEventRegistrationRemover(Action ToCall) 
  10:          {
  11:              this.CallOnDispose = ToCall; 
  12:          }
  13:   
  14:          public void Dispose() 
  15:          {
  16:              this.CallOnDispose.DynamicInvoke();
  17:          }
  18:      }
  19:  }

For your convenience, I’ve made these available for download here.

I also want to add that if you haven’t looked at the comments on the original post - there’s some really good stuff there (36 comments so far). Take a look.

  
If you liked this article, you might also like articles in these categories:


Check out my Best Content If you've got a minute, you might enjoy taking a look at some of my best articles.
I've gone through the hundreds of articles I've written over the past 4 years and put together a list of the best ones as ranked by my 2000+ readers.
You won't be disappointed.

Subscribe to my feedIf you'd like to get new articles sent to you when they're published, it's easy and free.
Subscribe right here.



Something on your mind? Got a question? I'd be thrilled to hear it.
Leave a comment below or email me, whatever works for you.

14 Comments

  1. Ayende Rahien Says:

    You can change this:
    this.CallOnDispose.DynamicInvoke();
    to this:
    this.CallOnDispose();

    And get the same behavior with static invocation.
    Same for the Raise() method.

    Do you really need scoping in here? Why not support this syntax?

    public class AddGameToCartMessageHandler :
    BaseMessageHandler
    {
    public override void Handle(AddGameToCartMessage m)
    {
    DomainEvents.GameReportedLost+= delegate{
    Bus.Return((int)ErrorCoes.GameReportedLost);
    };
    DomainEvents.CartIsFull += delegate{
    Bus.Return((int)ErrorCodes.CartIsFull);
    };

    using (ISession session = SessionFactory.OpenSession())
    using (ITransaction tx = session.BeginTransaction())
    using (.Register(cartIsFull))
    {
    ICart cart = session.Get(m.CartId);
    IGame g = session.Get(m.GameId);
    Â
    cart.Add(g);
    Â
    tx.Commit();
    }
    }
    Â
    }


  2. udidahan Says:

    Ayende,

    The problem with weakrefs, it turns out, is that the thread may run fast enough that garbage colleciton doesn’t occur in time. As such, we may have a dangling delegate being activated from the handling of a previous message by the same thread.

    That’s why I need scoping - to simplify cleanup.


  3. Ayende Rahien Says:

    But that is something that should be in the infrastructure.
    You put “clean domain events” as part of the life cycle.
    Putting it in the code means that you have concerns in your code that the infrastructure should handle.


  4. Chris Ortman Says:

    I like this much better than the first.
    Here’s a few things that come to mind that might be nice from a public api perspective

    1) conventions++
    using(DomainEvents.Register(cartIsFull, gameIsLost)) {

    }

    I /think/ we can parse out the variable name using the C# 3.0 Expression stuff.

    2) using…. the ability of returning something like IDisposableAction is great, but unless there’s great readability to be gained I don’t think I’m in favor of using using this way, is it that much better than something like With.Events(() => { });


  5. Tony Chevis Says:

    Udi,

    Maybe you should inject policies into the Cart. The policies are services which perform the checking. Just because the services live outside the domain doesn’t mean the domain is anemic. After all, you are adding intelligence to the domain and can do so using your IoC container.

    The service code would look something like:

    cart.enforcePolicies(GameOrderPolicies);
    if (cart.canAddGame(game))
    cart.add(game);
    else
    Bus.return(cart.brokenPolicies[0].PolicyName)

    Your domain only knows that there are certain policies which will be injected in, and those policies must be compliant before before adding a game.


  6. udidahan Says:

    Tony,

    I consider having the service layer use the result of one call to the domain to decide if another call to the domain is necessary to be taking domain logic out of the domain.

    In your example, I would prefer a single call:

    cart.Add(game, policies);

    The question is about the connection between the domain and the policies - what are the dependencies between them, how did the service layer get an instance of it, etc.


  7. udidahan Says:

    Ayende,

    It’s actually possible to have another message handler run at the end of the unit of work and do the clean-up for that thread.

    Still thinking about the generality of that solution.


  8. Ayende Rahien Says:

    You need to support the concept of IMessageModule, not just IMessageHandler.


  9. udidahan Says:

    Ayende,

    There is (kinda) support for that in the handling of the MessageReceived event of the transport - by setting the order of subscriptions you can do Before and After handling.


  10. How to create fully encapsulated Domain Models Says:

    […] Update: The new and improved solution is now available: Domain Events, Take 2. […]


  11. Neil Mosafi Says:

    Not too keen on having the static global events, why not have the events defined as properties on the domain model? I know you would say “but what if a child object raised the event?” but I would say that’s the parent object’s responsibility to listen to child object events and either handle them or raise its own events accordingly (or simply delegate via a custom add and remove handler).

    What would be the problem with that?


  12. udidahan Says:

    Neil,

    This creates extensibility and maintainability issues.

    Suppose I write another domain object which acts as an aggregate root in a different scenario making use of the current parent as a child. I’d have to remember to redefine that event on my object.

    Does that make sense?


  13. Daniel Fernandes Says:

    @Udi: There is a problem with [ThreadStatic] attribute with Web applications.
    I came across circumstances where the list of actions was null because I guess part of the HTTP request was handled by one thread and the rest by another one.
    I’ve removed this attribute and it’s fine now.


  14. udidahan Says:

    Daniel,

    Removing the [ThreadStatic] attribute causes a bug - an action on one thread by user A can call be into a different action previously registered by a different thread by user B.

    The overall guidance is that the domain model with its associated events should not be called within the web app itself. Rather, the domain model should be hosted in its own process, an application server if you will, which the web app sends messages to.

    Hope that helps.


Your comment...



If this is your first time commenting, it may take a while to show up.
I'm working to make that better.

Subscribe here to receive updates on comments.
  
   


Don't miss my best content
 
Locations of visitors to this page

Recommendations

Sam Gentile Sam Gentile, Independent WCF & SOA Expert
“Udi, one of the great minds in this area.
A man I respect immensely.”





Ian Robinson Ian Robinson, Principal Consultant at ThoughtWorks
"Your blog and articles have been enormously useful in shaping, testing and refining my own approach to delivering on SOA initiatives over the last few years. Over and against a certain 3-layer-application-architecture-blown-out-to- distributed-proportions school of SOA, your writing, steers a far more valuable course."

Simon Segal Simon Segal, Systems Integration Manager at LinFox
“Udi is one of the outstanding software development minds in the world today, his vast insights into Service Oriented Architectures and Smart Clients in particular are indeed a rare commodity. Udi is also an exceptional teacher and can help lead teams to fall into the pit of success. I would recommend Udi to anyone considering some Architecural guidance and support in their next project.”

Ohad Israeli Ohad Israeli, Chief Architect at Hewlett-Packard, Indigo Division
“When you need a man to do the job Udi is your man! No matter if you are facing near deadline deadlock or at the early stages of your development, if you have a problem Udi is the one who will probably be able to solve it, with his large experience at the industry and his widely horizons of thinking , he is always full of just in place great architectural ideas.
I am honored to have Udi as a colleague and a friend (plus having his cell phone on my speed dial).”

Eli Brin, Program Manager at RISCO Group
“We hired Udi as a SOA specialist for a large scale project. The development is outsourced to India. SOA is a buzzword used almost for anything today. We wanted to understand what SOA really is, and what is the meaning and practice to develop a SOA based system.
We identified Udi as the one that can put some sense and order in our minds. We started with a private customized SOA training for the entire team in Israel. After that I had several focused sessions regarding our architecture and design.
I will summarize it simply (as he is the software simplist): We are very happy to have Udi in our project. It has a great benefit. We feel good and assured with the knowledge and practice he brings. He doesn’t talk over our heads. We assimilated nServicebus as the ESB of the project. I highly recommend you to bring Udi into your project.”

Yoel Arnon Yoel Arnon, MSMQ Expert
“Udi has a unique, in depth understanding of service oriented architecture and how it should be used in the real world, combined with excellent presentation skills. I think Udi should be a premier choice for a consultant or architect of distributed systems.”

Vadim Mesonzhnik, Development Project Lead at Polycom
“When we were faced with a task of creating a high performance server for a video-tele conferencing domain we decided to opt for a stateless cluster with SQL server approach. In order to confirm our decision we invited Udi.

After carefully listening for 2 hours he said: "With your kind of high availability and performance requirements you don’t want to go with stateless architecture."

One simple sentence saved us from implementing a wrong product and finding that out after years of development. No matter whether our former decisions were confirmed or altered, it gave us great confidence to move forward relying on the experience, industry best-practices and time-proven techniques that Udi shared with us.
It was a distinct pleasure and a unique opportunity to learn from someone who is among the best at what he does.”

Jack Van Hoof Jack Van Hoof, Enterprise Integration Architect at Dutch Railways
“Udi is a respected visionary on SOA and EDA, whose opinion I most of the time (if not always) highly agree with. The nice thing about Udi is that he is able to explain architectural concepts in terms of practical code-level examples.”

Nick Malik Nick Malik, Enterprise Architect at Microsoft Corporation
“You are an excellent speaker and trainer, Udi, and I've had the fortunate experience of having attended one of your presentations. I believe that you are a knowledgable and intelligent man.”

Sean Farmar Sean Farmar, Chief Technical Architect at Candidate Manager Ltd
“Udi has provided us with guidance in system architecture and supports our implementation of NServiceBus in our core business application.

He accompanied us in all stages of our development cycle and helped us put vision into real life distributed scalable software. He brought fresh thinking, great in depth of understanding software, and ongoing support that proved as valuable and cost effective.

Udi has the unique ability to analyze the business problem and come up with a simple and elegant solution for the code and the business alike.
With Udi's attention to details, and knowledge we avoided pit falls that would cost us dearly.”

Motty Cohen, SW Manager at KorenTec Technologies
“I know Udi very well from our mutual work at KorenTec. During the analysis and design of a complex, distributed C4I system - where the basic concepts of NServiceBus start to emerge - I gained a lot of "Udi's hours" so I can surely say that he is a professional, skilled architect with a fresh ideas and unique perspective for solving complex architecture challenges. His ideas, concepts and parts of the artifacts are the basis of several state-of-the-art C4I systems that I was involved in their architecture design.”

Aaron Jensen Aaron Jensen, VP of Engineering at Eleutian Technology
“Awesome. Just awesome.

We’d been meaning to delve into messaging at Eleutian after multiple discussions with and blog posts from Greg Young and Udi Dahan in the past. We weren’t entirely sure where to start, how to start, what tools to use, how to use them, etc. Being able to sit in a room with Udi for an entire week while he described exactly how, why and what he does to tackle a massive enterprise system was invaluable to say the least.

We now have a much better direction and, more importantly, have the confidence we need to start introducing these powerful concepts into production at Eleutian.”

Gad Rosenthal Gad Rosenthal, Department Manager at Retalix
“A thinking person. Brought fresh and valuable ideas that helped us in architecting our product. When recommending a solution he supports it with evidence and detail so you can successfully act based on it. Udi's support "comes on all levels" - As the solution architect through to the detailed class design. Trustworthy!”

Robert Lewkovich, Product / Development Manager at Eggs Overnight
“Udi's advice and consulting were a huge time saver for the project I'm responsible for. The $ spent were well worth it and provided me with a more complete understanding of nServiceBus and most importantly in helping make the correct architectural decisions earlier thereby reducing later, and more expensive, rework.”

Ray Houston Ray Houston, Director of Development at TOPAZ Technologies
“Udi's SOA class made me smart - it was awesome.

The class was very well put together. The materials were clear and concise and Udi did a fantastic job presenting it. It was a good mixture of lecture, coding, and question and answer. I fully expected that I would be taking notes like crazy, but it was so well laid out that the only thing I wrote down the entire course was what I wanted for lunch. Udi provided us with all the lecture materials and everyone has access to all of the samples which are in the nServiceBus trunk.

Now I know why Udi is the "Software Simplist." I was amazed to find that all the code and solutions were indeed very simple. The patterns that Udi presented keep things simple by isolating complexity so that it doesn't creep into your day to day code. The domain code looks the same if it's running in a single process or if it's running in 100 processes.”

Liron Levy, Team Leader at Rafael
“I've met Udi when I worked as a team leader in Rafael. One of the most senior managers there knew Udi because he was doing superb architecture job in another Rafael project and he recommended bringing him on board to help the project I was leading.
Udi brought with him fresh solutions and invaluable deep architecture insights. He is an authority on SOA (service oriented architecture) and this was a tremendous help in our project.
On the personal level - Udi is a great communicator and can persuade even the most difficult audiences (I was part of such an audience myself..) by bringing sound explanations that draw on his extensive knowledge in the software business. Working with Udi was a great learning experience for me, and I'll be happy to work with him again in the future.”

Eytan Michaeli Eytan Michaeli, CTO Korentec
“Udi was responsible for a major project in the company, and as a chief architect designed a complex multi server C4I system with many innovations and excellent performance.”

Evgeny-Hen Osipow, Head of R&D at PCLine
“Udi has helped PCLine on projects by implementing architectural blueprints demonstrating the value of simple design and code.”

Nimrod Peleg Nimrod Peleg, Lab Engineer at Technion IIT
“One of the best programmers and software engineer I've ever met, creative, knows how to design and implemet, very collaborative and finally - the applications he designed implemeted work for many years without any problems!”

Consult with Udi

Guest Authored Books
Chapter: Introduction to SOA    Article: The Enterprise Service Bus and Your SOA



Creative Commons License  © Copyright 2008, Udi Dahan. email@UdiDahan.com