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

Domain Events – Salvation

Sunday, June 14th, 2009.

sphere
I’ve been hearing from people that have had a great deal of success using the Domain Event pattern and the infrastructure I previously provided for it in Domain Events – Take 2. I’m happy to say that I’ve got an improvement that I think you’ll like. The main change is that now we’ll be taking an approach that is reminiscent to how events are published in NServiceBus.

Background

Before diving right into the code, I wanted to take a minute to recall how we got here.

It started by looking for how to create fully encapsulated domain models.

The main assertion being that you do *not* need to inject anything into your domain entities.

Not services. Not repositories. Nothing.

Just pure domain model goodness.

Make Roles Explicit

I’m going to take the advice I so often give. A domain event is a role, and thus should be represented explicitly:

   1:  public interface IDomainEvent {}

If this reminds you of the IMessage marker interface in nServiceBus, you’re beginning to see where this is going…

How to define domain events

A domain event is just a simple POCO that represents an interesting occurence in the domain. For example:

   1:  public class CustomerBecamePreferred : IDomainEvent 
   2:  {
   3:      public Customer Customer { get; set; }
   4:  }

For those of you concerned about the number of events you may have, and therefore are thinking about bunching up these events by namespaces or things like that, slow down. The number of domain events and their cohesion is directly related to that of the domain model.

If you feel the need to split your domain events up, there’s a good chance that you should be looking at splitting your domain model too. This is the bottom-up way of identifying bounded contexts.

How to raise domain events

In your domain entities, when a significant state change happens you’ll want to raise your domain events like this:

   1:  public class Customer
   2:  {
   3:      public void DoSomething()
   4:      {
   5:          DomainEvents.Raise(new CustomerBecamePreferred() { Customer = this });
   6:      }
   7:  }

We’ll look at the DomainEvents class in just a second, but I’m guessing that some of you are wondering “how did that entity get a reference to that?” The answer is that DomainEvents is a static class. “OMG, static?! But doesn’t that hurt testability?!” No, it doesn’t. Here, look:

Unit testing with domain events

One of the things we’d like to check when unit testing our domain entities is that the appropriate events are raised along with the corresponding state changes. Here’s an example:

   1:  public void DoSomethingShouldMakeCustomerPreferred()
   2:  {
   3:      var c = new Customer();
   4:      Customer preferred = null;
   5:   
   6:      DomainEvents.Register<CustomerBecamePreferred>(
   7:          p => preferred = p.Customer
   8:              );
   9:   
  10:      c.DoSomething();
  11:      Assert(preferred == c && c.IsPreferred);
  12:  }

As you can see, the static DomainEvents class is used in unit tests as well. Also notice that you don’t need to mock anything – pure testable bliss.

Who handles domain events

First of all, consider that when some service layer object calls the DoSomething method of the Customer class, it doesn’t necessarily know which, if any, domain events will be raised. All it wants to do is its regular schtick:

   1:  public void Handle(DoSomethingMessage msg)
   2:  {
   3:      using (ISession session = SessionFactory.OpenSession())
   4:      using (ITransaction tx = session.BeginTransaction())
   5:      {
   6:          var c = session.Get<Customer>(msg.CustomerId);
   7:          c.DoSomething();
   8:   
   9:          tx.Commit();
  10:      }
  11:  }

The above code complies with the Single Responsibility Principle, so the business requirement which states that when a customer becomes preferred, they should be sent an email belongs somewhere else.

Notice that the key word in the requirement – “when”.

Any time you see that word in relation to your domain, consider modeling it as a domain event.

So, here’s the handling code:

   1:  public class CustomerBecamePreferredHandler : Handles<CustomerBecamePreferred>
   2:  { 
   3:     public void Handle(CustomerBecamePreferred args)
   4:     {
   5:        // send email to args.Customer
   6:     }
   7:  } 

This code will run no matter which service layer object we came in through.

Here’s the interface it implements:

   1:  public interface Handles<T> where T : IDomainEvent
   2:  {
   3:      void Handle(T args); 
   4:  } 

Fairly simple.

Please be aware that the above code will be run on the same thread within the same transaction as the regular domain work so you should avoid performing any blocking activities, like using SMTP or web services. Instead, prefer using one-way messaging to communicate to something else which does those blocking activities.

Also, you can have multiple classes handling the same domain event. If you need to send email *and* call the CRM system *and* do something else, etc, you don’t need to change any code – just write a new handler. This keeps your system quite a bit more stable than if you had to mess with the original handler or, heaven forbid, service layer code.

Where domain event handlers go

These handler classes do not belong in the domain model.

Nor do they belong in the service layer.

Well, that’s not entirely accurate – you see, there’s no *the* service layer. There is the part that accepts messages from clients and calls methods on the domain model. And there is another, independent part that handles events from the domain. Both of these will probably make use of a message bus, but that implementation detail shouldn’t deter you from keeping each in their own package.

The infrastructure

I know you’ve been patient, reading through all my architectural blah-blah, so here it is:

   1:  public static class DomainEvents
   2:  { 
   3:      [ThreadStatic] //so that each thread has its own callbacks
   4:      private static List<Delegate> actions;
   5:   
   6:      public static IContainer Container { get; set; } //as before
   7:   
   8:      //Registers a callback for the given domain event
   9:      public static void Register<T>(Action<T> callback) where T : IDomainEvent
  10:      {
  11:         if (actions == null)
  12:            actions = new List<Delegate>();
  13:   
  14:         actions.Add(callback);
  15:     }
  16:   
  17:     //Clears callbacks passed to Register on the current thread
  18:     public static void ClearCallbacks ()
  19:     {
  20:         actions = null;
  21:     }
  22:   
  23:     //Raises the given domain event
  24:     public static void Raise<T>(T args) where T : IDomainEvent
  25:     {
  26:        if (Container != null)
  27:           foreach(var handler in Container.ResolveAll<Handles<T>>())
  28:              handler.Handle(args);
  29:   
  30:        if (actions != null)
  31:            foreach (var action in actions)
  32:                if (action is Action<T>)
  33:                    ((Action<T>)action)(args);
  34:     }
  35:  } 

Notice that while this class *can* use a container, the container isn’t needed for unit tests which use the Register method.

When used server side, please make sure that you add a call to ClearCallbacks in your infrastructure’s end of message processing section. In nServiceBus this is done with a message module like the one below:

   1:  public class DomainEventsCleaner : IMessageModule
   2:  { 
   3:      public void HandleBeginMessage() { }
   4:   
   5:      public void HandleEndMessage()
   6:      {
   7:          DomainEvents.ClearCallbacks();
   8:      }
   9:  }

The main reason for this cleanup is that someone just might want to use the Register API in their original service layer code rather than writing a separate domain event handler.

Summary

Like all good things in life, 3rd time’s the charm.

It took a couple of iterations, and the API did change quite a bit, but the overarching theme has remained the same – keep the domain model focused on domain concerns. While some might say that there’s only a slight technical difference between calling a service (IEmailService) and using an event to dispatch it elsewhere, I beg to differ.

These domain events are a part of the ubiquitous language and should be represented explicitly.

CustomerBecamePreferred is nothing at all like IEmailService.

In working with your domain experts or just going through a requirements document, pay less attention to the nouns and verbs that Object-Oriented Analysis & Design call attention to, and keep an eye out for the word “when”. It’s a critically important word that enables us to model important occurrences and state changes.

What do you think? Are you already using this approach? Have you already tried it and found it broken in some way? Do you have any suggestions on how to improve it?

Let me know – leave a comment below.

  
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 6 years and put together a list of the best ones as ranked by my 5000+ 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.

Follow me on Twitter Follow me on Twitter @UdiDahan.



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.

187 Comments

  1. Szymon Pobiega Says:

    Good title for the post. It really _solved_ my problem with my application.

    Application works something like that: every few seconds a service layer method is called by a scheduler. This method gets from the database Settlement objects in particular state (to-be-settled) and calls on them ‘Settle’ method to do the accounting. The requirement says that once settlement is done, another application should be notified.

    My original approach was to implement the notification in service layer just after call to the ‘Settle’ method, but I wasn’t happy with this design.

    Now I would use your domain events solution to encapsulate this ‘when’ requirement in the domain model.


  2. DotNetShoutout Says:

    Domain Events – Salvation – Udi Dahan…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…


  3. DaRage Says:

    This seems like a big deal and may be it should be identified as a DDD pattern along with Aggregate, Service, Repository and other DDD patterns. I would like to hear what Eric Evans says about it.

    To me it shounds like a very good idea to capture the domain model events explicitly since they certainly come up in conversations. Or is it another layer of indirection? ok a question, can event hanldles raise events on their own or is it an anit pattern?


  4. udidahan Says:

    Szymon,

    Glad that it was helpful.


  5. udidahan Says:

    DaRage,

    Eric gave a talk in QCon London 2009 which was written up by Gojko here:

    http://gojko.net/2009/03/12/qcon-london-2009-eric-evans-what-ive-learned-about-ddd-since-the-book/

    In it, he talks about the need for the Domain Event pattern in DDD.

    To your question, I would probably stay away from those handlers raising domain events themselves – that responsibility lies with the domain model. That being said, those handlers definitely could use a message bus to publish a corresponding (or higher level) event that other apps/services could be subscribed to.

    Does that make sense?


  6. DaRage Says:

    Thanks for the link Udi. then how do you handle scenario like “when this even happens, this should happen”. or maybe what you call saga in nservicebus.


  7. Tobin Harris Says:

    Love the idea of domain events being explicit, and all the code looks great.

    Had you thought about making the events persistent in the database rather than as a static list? My worry is that events would get lost in the case of a crash. Or is that why you mentioned using a service bus (I haven’t grokked service busses yet!)?


  8. Ryan Roberts Says:

    A definite improvement. I have been happily using a variant of your original work that uses multiple generic parameters to autowired pipelines, as I needed the ability to control the order of handler execution and abort operations.

    I had been considering a refactoring to explicit message classes to remove some of the eye searing angle brackets, but have not so far needed more than 2 tuples.

    Would mutability of messages be problematic here when they are not in a distributed system? Pushing cancellation into the message itself seems possibly neater than return false from a pipeline processing method.


  9. Steve Says:

    Fantastic!

    Not to be a pain, but could you provide a small little sample of how to tie this all together ?

    Thanks!

    Do you think it would be bad to use this sort of event raising system to add entities to a unit of work?


  10. udidahan Says:

    DaRage,

    “when this event happens, this should happen”

    That often happens in a different bounded context than the one that raised the event. In which case, the first event handler would publish the event on a message bus. The other bounded context would be subscribed to that event, and in its handling logic do the “this should happen” part.

    Does that answer your question?


  11. udidahan Says:

    Tobin,

    Notice that dispatching events is done primarily to event handlers, which are registered in the container at application start. In short, the list doesn’t have to be persistent.

    Does that make sense?


  12. udidahan Says:

    Ryan,

    It sounds like you’re trying to implement some kind of workflow with these patterns (canceling stuff). That’s not really what they’re designed for. These events are truly fire & forget


  13. udidahan Says:

    Steve,

    I’m not really sure how events would fit into simply adding entities to a unit of work – not sure what value it would bring.

    About a sample, well, hopefully I’ll get around to it someday :-)


  14. Arnon Rotem-Gal-Oz Says:

    We’re doing something similar with business events between services where we can do things like
    var eventDetails = new InteractionStartedEvent(SessionId, url);
    eventBroker.RaiseSagaEvent(sagaId, eventDetails);

    I wrote a little about it here : http://www.rgoarchitects.com/nblog/2008/10/18/EventingInWCF.aspx


  15. udidahan Says:

    Arnon,

    That’s similar to how it’s done in nServiceBus, just that the interpretation of the event as belonging to a saga is done by subscribers – not the publisher.


  16. Arnon Rotem-Gal-Oz Says:

    Udi
    Hmm, I distinguish between events and saga events in the sense that Sagas are done on a shared context. Since I think that this shared context is also important to the publisher it is up to it to say which saga(s) the event is relevant to.
    If a service needs/interested in sending a general out-of-context event it can do that by raising a regular event (eventBroker.RaiseEvent) – receivers can choose to relate to that events in the internal representations of sagas that they hold
    This allows supporting the nServiceBus behavior as well.
    I have to say, though, that I usually find the first form (saga events) is more natural fit (in our context naturally…)


  17. udidahan Says:

    Arnon,

    While a publisher can put any information they want in the events they publish (including a saga Id), the assumptions it can make about subscribers are limited. This is even more true when we’re talking about publishers and subscribers belonging to different business services.

    Maybe put up a blog post describing more about the specifics of your context…


  18. Arnon Rotem-Gal-Oz Says:

    Udi,
    If you see the signature of the RaiseSagaEvent method you can see that the event isn’t required to have a saga Id in it (it is a convenience when the business process is all internal, when we need to integrate with external system we usually add a bridge service as an intermediate but that’s another story)
    What is needed is to pass the SagaID to the eventBroker (the first parameter) and then the infrastructure does the routing (e.g. we can route to specific service instances for stateful services)

    Anyway, I guess you are right and a blog post will explain it better :)


  19. Jonathan Oliver Says:

    Udi,

    Watch out on that [ThreadStatic] attribute–it can bite you hard in ASP.NET:

    http://bit.ly/6CWZl


  20. Matt Says:

    Hi Udi,

    Great series of posts. Could you elaborate a little on how this would work in a context where there’s a UI involved. For instance, in the example that you initially gave, if someone clicked a “Checkout” button or similar in a MVC web app, how would you suggest the events that represent a problem with the cart contents are handled in such a way to communicate the problems to the UI?

    Thanks,
    Matt


  21. udidahan Says:

    Jonathon,

    I guess that I always use a domain model in an application server so haven’t been bit by that yet. As a general purpose infrastructure, though, it should be addressed.

    Thanks for the heads-up.


  22. udidahan Says:

    Matt,

    In the case where I’d need feedback to the user, I’d go with running the domain model in process with the web app. Then, I’d have a module that listened to those events, putting out errors to the UI.

    The problem is that MVC isn’t currently designed to handle composite scenarios that well, and what you’re looking for is best addressed by that kind of composite pattern – where multiple independent elements can build together the same response.

    Hope that helps.


  23. Eb Says:

    When is the handler “registered”? Am I missing something?


  24. udidahan Says:

    Eb,

    The handler would be registered in the container at application startup.

    Does that make sense?


  25. Jason Diamond Says:

    Do you use domain events for persistence concerns like loading and saving customers?

    If persistence concerns are being handled by repositories, it seems like you’d still need to inject stub repositories into the domain model for testing purposes.


  26. udidahan Says:

    Jason,

    Since these domain events represent occurrences that originate from within the domain, I don’t see their use so much for loading and saving.

    I’m not so sure as to why one would need to let entities reference repositories in the first place, let alone for testing purposes.

    Hope that makes sense.


  27. Andy Z Says:

    Udi,

    Thanks for all of the information. I am someone who has been buried in a huge pile of legacy C++ code for a few years and is trying to get up to speed with the latest .Net architecture/design approaches so that I can set a target for where I’d like to migrate all of this code. I’ve done a little prototyping and a fair bit of reading, but nothing more, so please forgive me if I’m off base with this point.

    This isn’t a problem with your design, but is more of a warning about how the events themselves should be used when received. My point is that these events are fired out of the “domain universe” and for many applications what happens in this universe doesn’t become “real” until the domain objects are serialized back out into persistent storage.

    I think that sending an email (in our universe) based on an event coming from the domain universe is premature. What if the changes to the in memory domain objects are aborted after the event is fired? You will have sent an email for something that effectively never happened.

    So, my suggestion would be to try to follow “what happens in the domain universe stays in the domain universe”. In this example, the event handler should perhaps create an email domain object as part of the same context so that the email and other domain objects are persisted together. Later (or perhaps as a side effect of the email domain object being persisted) the actual email can be sent.

    Alternatively the service layer could hold on to the email request until the actual persistence happens. Ideally there would be a general purpose mechanism for holding such actions which need to be accumulated and then performed on commit. Ideally these actions would be part of the transaction which commits the domain objects to their storage.

    Thanks again,
    Andy


  28. Mark Seemann Says:

    Thank you for the post – I’ll add Domain Events to my architectural toolbox.

    However, if you hadn’t written “when some service layer object calls the DoSomething method of the Customer class, it doesn’t necessarily know which, if any, domain events will be raised”, I would have been wondering why you spent so much time re-inventing Events (or the Observer pattern). As I now understand it, the reason is that this implementation give us loosely coupled events, but you might want to state this a bit more explicitly :)

    As might be expected, I don’t agree that the design doesn’t hurt testability. Sure, it’s possible to test your Domain Events, but at the very least you will need to remember to implement Implicit Teardown where you call ClearCallbacks. If not, you will have Test Interdependence (an xUnit anti-pattern). To me, that is a test smell.

    Personally, I’d prefer injecting a Domain Event Service into the Domain Object, because that would be an instance that the garbage collector would clean up automatically. YMMV…


  29. udidahan Says:

    Andy,

    You’re right about not sending email as a part of the domain event handler – I short-cutted my usual recommendation of using transactional messaging to communicate with another endpoint which does the actual email sending.

    Thanks for pointing it out.


  30. udidahan Says:

    Mark,

    Thanks for your comments. While the option you outline may be a little cleaner for tests that deal with events, those tests which only deal with state would need to remember to inject a stub domain event service, otherwise those tests would fail.

    As you said, YMMV :-)


  31. Jason Diamond Says:

    Udi,

    This may be veering off the topic of domain events, but I’m intrigued by your position and really want to understand it better.

    If invoking a method on an entity changes the state of that entity, how will that state get persisted? Not wanting to reference a repository is why I asked if raising an event would be an appropriate way to notify whoever’s listening that the entity needs to be saved.

    Also, if invoking a method on an entity requires state or even behavior from some other entity, how will that other entity be retrieved?

    I’m all for removing all references to repositories from my entities, but am not clear about how to do that yet.

    Thanks.


  32. udidahan Says:

    Jason,

    The ORM that retrieved the entity in the first place checks if it’s dirty (had it’s state changed) when completing the transaction. If so, the entity gets persisted.

    When one entity calls another entity, the second entity can be lazy loaded by the ORM, or eagerly fetched together with the first, depending on how the ORM was configured or the Get call was performed. In other words, all you need is to set up direct references between your entities and configure those relationships in the ORM.

    Does that make sense?


  33. ryzam Says:

    Hi Udi
    I’m not sure is it related with this article or not what i’m trying to ask. Can a message contains entity object?. For example i have entity object called
    Profile
    – Id
    – Name
    – Email
    – …

    and

    UserAccount
    – Id,
    – UserName
    – Password
    – …

    I have a use case to create Profile and User account. For that i create a message called CreateProfileAndUserAccount. My question is what property should in the CreateProfileAndUserAccount?

    Option 1
    public class CreateProfileAndUserAccount
    {
    public Profile Profile {set; get;}
    public UserAccount UserAccount {set; get;}
    }

    Option 2
    public class CreateProfileAndUserAccount
    {
    public string FullName {set; get;}
    public string Email {set; get;}
    public string UserName {set; get;}

    }

    I hope can get some idea from you.

    Thanks


  34. Szymon Pobiega Says:

    I tried to use this pattern in another DDD-style application and got confused when designing a service layer method to create new aggregate root object.

    I implemented validation logic in the entity constructor. It works just fine. But I could not find out how to communicate to service layer, that some validation events occured and either:
    * the transactions should not be committed
    * session.Save(myNewEntity) should not be called

    Do you have any ideas how to solve this problem (apart of “using” exceptions)? I thought about a special event like “No events occured” which could be wired to call to session.Save.


  35. Sean Kearon Says:

    Following from @Tobin’s comment…if we do persist the events, do you have any thoughts on how to recognise that all event’s handlers have received the event (so I know when to close the event)?


  36. udidahan Says:

    ryzam,

    It sounds like what you have here is a two step process – the first is the creation of the user. When that step completes, an event is raised, which kicks of the second step – the creation of the profile.

    Each of these two steps would be its own transaction.

    Does that answer your question?


  37. udidahan Says:

    Sean,

    It sounds like you’d like to use this to model some long-running process – ergo your desire to persist the events for fault-tolerance.

    That’s not what it’s for.

    Use the saga pattern in that case. It has the explicit concept of “closing the event” – completing the long-running process. Events are descriptions of occurrences in the past – “closing an event” doesn’t really mean anything about events.

    Does that make sense?


  38. Sean Kearon Says:

    Hi Udi

    Thanks, that does make sense, but I was thinking more about the handlers being subscribers to the event and the case when not all of the handlers are online when the event was published. If the event were persistent then subscribing handlers would be activated when they next come online.

    (Sorry, “closing” was a typo, I meant “deleting” as in removing it from the persistence or marking it as complete!)


  39. udidahan Says:

    Sean,

    The handlers can’t not be “online” – they run in-process with the domain model. While those handlers can forward the event / send messages to other endpoints, and those endpoints may be offline, that is handled by a queued transport very simply – you may want to look at nServiceBus for some examples.

    Hope that makes sense.


  40. Sean Kearon Says:

    Udi

    Aha – I was missing that! It makes sense now.

    Thanks again

    Sean


  41. Don’t Create Aggregate Roots Says:

    [...] previous post on Domain Events left some questions about how aggregate roots should be created unanswered. It would actually be [...]


  42. Frank Says:

    Udi,
    I understood your Domain Events – Take 2, but you lost me in this most recent version with the addition of the Container. Could you please explain what this is and how you go about using it?


  43. Summary 03.07.2009 – 07.07.2009 « Bogdan Brinzarea’s blog Says:

    [...] Dahan has two excellent posts about domain events and the creation of aggregate [...]


  44. Event Aggregator Using the Magnum Pipeline - PhatBoyG (Chris Patterson) - Says:

    [...] the past few weeks, both Udi Dahan and Jeremy D. Miller have posted on events. Udi posted about domain events, while Jeremy posted [...]


  45. Giorgio Sironi Says:

    Udi,
    I was thinking about the use of a static class, but my thoughts were so long that I have to responde in another post. I do not agree that using one in an entity object is a clean idea, so I wanted to discuss the problem:
    http://giorgiosironi.blogspot.com/2009/07/global-state-is-rarely-salvation.html
    Feel free to leave a comment. :)


  46. Pat Maddox Says:

    I notice that the event contains a reference to the customer domain object…I was under the impression that you wanted to use IDs in the event instead of domain objects, so that other bounded contexts can look it up as needed. Why do you use a customer object in this case, and how do you decide when to use a domain object or an id?


  47. ryzam Says:

    Hi Udi

    I think maybe my question was not clear. I would like to know the structure of message, can message contains entity or it only can hold a value object. For example if I have an entity of User and Profile and for the creation of the process i will use CreateUserProfileMessage. My question is about the structure of CreateUserProfileMessage. I have 2 option how to structure the message

    Option 1

    public class CreateUserProfileMessage
    {
    public Profile UserProfile {set; get;}

    public Account UserAccount {set; get;}
    }

    Option 2

    public class CreateUserProfileMessage
    {
    public string Name {set; get;}
    public string Username {set; get;}
    public string Password {set; get;}
    }

    Which one is the correct way to structure the message?

    Thanks


  48. udidahan Says:

    Frank,

    The container is an object that enables us to register objects in it (primarily at application startup) and then query for those objects at runtime.

    This decrease coupling as calling code isn’t dependent on the concrete implementation types of the called code.

    I suggest you take a look at some of the literature on Dependency Injection / Inversion of Control.

    Hope that helps.


  49. udidahan Says:

    Giorgio,

    I’ve read through your post and you seem to want to unit-test a single entity. Unfortunately, the domain model is actually the unit, not a single entity. Domain events are just as much a part of the domain model as entities and the static DomainEvents class is supporting infrastructure (which you could choose to unit test independently if you felt like it).

    Hope that makes sense.


  50. udidahan Says:

    Pat,

    Events that pass between bounded contexts (on some kind of bus) should indeed only contain IDs. Domain events that occur within a single bounded context should contain the full entity as upstream handlers may need the additional information to make decisions within that same bounded context.

    Hope that makes sense.


  51. udidahan Says:

    ryzam,

    I think I understand your question now.

    Messages are themselves value objects and so should only contain value objects. The second message type is the preferred one, assuming that Profile and Account are entities in the domain model.

    Does that answer your question?


  52. MSDN Article: ‘Employing the Domain Model Pattern’ at { null != Steve } Says:

    [...] ‘Domain Events – Salvation’ by Udi [...]


  53. ryzam Says:

    “The above code complies with the Single Responsibility Principle, so the business requirement which states that when a customer becomes preferred, they should be sent an email belongs somewhere else.

    Notice that the key word in the requirement – “when”.

    Any time you see that word in relation to your domain, consider modeling it as a domain event.”

    Udi based on the statement, “when” is referred to the process from one entity that will affected other entity right? But if the changes is within the entity itself do we need to use DomainEvent.

    For example , let say we have Customer entity and the use case for this process is “Customer credit balance should increased when add credit”. Here the changes of data only happen to Customer

    public class Customer
    {
    public decimal CreditBalance {set; get;}

    public void AddCredit(decimal creditValue)
    {
    //Do we need to call domain event here?
    }

    }

    My question, maybe very basic, but just to make it more clear
    Thanks


  54. udidahan Says:

    Ryzam,

    I understand the confusion.

    The thing is that you’re requirement is equivalent to:

    “Adding credit to a customer should result in an increased credit balance by the amount that was added.”

    The word “when” is an indicator, not proof positive, that a domain event may be appropriate. One of the the things we’re looking to do here is represent business occurrences with their corresponding technological element – the event.

    In your example, if the creditValue passed in was negative, we may decide to raise a domain event indicating that problem, rather than, say, throwing an exception.

    Hope that makes sense.


  55. altnet 2009 « Hari Krishnan Says:

    [...] was a discussion about Domain Events based on Udi Dahan’s blog. A varied approach to handle requirements like sending emails when a domain entity [...]


  56. Blair Davidson Says:

    Hi If you creating an event like BecamePreffered and sending and email in the handler what happens if you save to the db after and it fails then then they are not preferred and an email has been sent?

    Thoughts


  57. udidahan Says:

    Blair,

    Quoting the relevant part of the article:

    “[In domain event handlers] you should avoid performing any blocking activities, like using SMTP or web services. Instead, prefer using one-way messaging to communicate to something else which does those blocking activities.”

    Sending a message on a bus is a transactional activity that will roll back together with the DB. Only when the tx commits, will the message be sent to the target endpoint, and it will do the email sending then.

    Does that answer your question?


  58. Jørn Wildt Says:

    Hi Udi

    Why is it that your approach is better than using plain old .NET events?

    Consider this:

    // Same as IDomainEvent
    class CustomerBecamePreferredEventArgs : EventArgs {…}

    // Event declaration
    public static event EventHandler CustomerBecamePreferred;

    // My handler
    public class MyCustomerBecamePreferredHandler
    {
    public void Handle(object s, CustomerBecamePreferredEventArgs args)
    {

    }
    }

    // Register
    CustomerBecamePreferred += new MyCustomerBecamePreferredHandler().Handle;

    // Fire
    CustomerBecamePreferred(null, new CustomerBecamePreferredEventArgs(…));

    I can see some advantages with your approach, but want to be sure about the “why” you are doing event management your way.

    Advantages I can see with your approach:

    - It seems like there is less code to write for each event (you avoid declaring the actual event, you only need the event args).
    - There is no need for a pseudo “sender” object (can although be avoided with your own definition of EventHandler).
    - You could auto-register handlers in the same way as NServiceBus does.

    /Jørn


  59. udidahan Says:

    Jørn,

    It sounds like you’ve pretty much answered yourself :-)


  60. Richard Dingwall Says:

    Hi Udi, we’ve started using your domain events pattern in a big legacy app we’re slowly refactoring, and they are fantastic.

    But a question has arisen about ‘Where domain event handlers go’. Imagine the business has another rule that ‘when a customer becomes preferred, we should increase their credit limit’. This rule is part of the business domain, so shouldn’t the handler for it be in the domain layer??


  61. udidahan Says:

    Richard,

    “When a customer becomes preferred, we should increase their credit limit”

    … is a great example for leading to bounded contexts.

    One context makes the customer preferred, and publishes an event on a message bus of sorts.
    When that message arrives at the other bounded context, it handles it and raises the credit limit.

    There may be a period of time where the customer is preferred but their credit limit hasn’t been raised yet, as the message bus durably and transactionally moves the message.

    Hope that answers your question


  62. Bryan Prendergast Says:

    Udi,

    I really like your concept of making roles explicit. Do you retain this concept in Domain Events? I don’t want to get off-topic but I am curious.

    For instance, if you don’t implement a handler for Handles . . . what happens?

    My personal takeaway and excitement over making roles explicit is that you can always implement a Handles.

    In other words, you always implement a Default for every domain event, with the “green case” implementation, and then, you only implement a specific Handles if and only if you really need to do something very specific and different from the default case, only if you need to override. This kinda matches the virtual method vs. overriden method concept from C# . . .

    For instance, here’s an example of a ValidatorService in Prism that relies on a default case:

    public class ValidatorService
    {
    public ValidatorService() { }

    public void Validate(IUnityContainer container, T arg) where T: IEntity
    {
    try
    {
    if (container.Resolve<IValidator>() != null)
    {
    container.Resolve<IValidator>().Validate(container, arg);
    }
    }
    catch (ResolutionFailedException rException)
    {
    container.Resolve<IValidator>().Validate(container, new DefaultEntity());
    }
    }
    }

    Are you still following this awesome pattern? I believe this is what you were implying in your “making roles explicit” talk . . .

    It means that I can code my Contact view or viewmodel up this way:

    ValidatorService.Validate(Container, _innerContact);

    And if I haven’t yet implemented a ContactValidator yet, then it will use the default, and if I later add a ContactValidator, I don’t need to change this line of code, anywhere it exists, it will merely call my ContactValidator’s Validate method instead of the default going forward . . .

    thanks,
    Bryan


  63. Bryan Prendergast Says:

    fyi . . . my comment didn’t come through quite right.

    “For instance, if you don’t implement a handler for Handles . . . what happens?

    My personal takeaway and excitement over making roles explicit is that you can always implement a Handles.”

    SHOULD BE

    For instance, if you don’t implement a handler for Handles<CustomerBecamePreferred> … what happens?

    My personal takeaway and excitement over making roles explicit is that you can always implement a Handles<DefaultEntityBecamePreferred>

    Didn’t know it would have trouble interpreting angle brackets.


  64. Bryan Prendergast Says:

    Small correction to my code . . .

    Here I pass in the IEntity arg into the constructor of the DefaultEntity, in case you need to do anything to it there in the DefaultValidator class: {

    validateResult = container.Resolve<IValidator>().Validate(container, new DefaultEntity(arg));

    }

    I also changed Validate to return a bool. This is in-progress code . . .


  65. Jeff Says:

    Udi, how is your approach different from Jeremy Miller’s Event Aggregator?

    Would be cool if you could comment on non-container specific details.


  66. Martin Rosén-Lidholm Says:

    @Andy (post #27)

    I’ve made the DomainEvents itself accumulate event handling that needs to be deferred.

    Instead of being handled immediately, they are instead added to a list of IDomainEvent, Action pairs.

    When later the repository raises a SaveOk event, they are carried out.


  67. Jørn Wildt Says:

    Udi, I just watched your remake of Make Roles Explicit on NDC2009. I think your last part explains pretty good all the benefits of your domain event approach. Thanks.


  68. udidahan Says:

    Bryan,

    I’m glad that you’re finding these patterns making sense and providing value. I think, though, that you may be taking things to an overly generic extreme – not just anything becomes preferred, only customers. Orders may get canceled – not preferred, and we certainly don’t want customers getting canceled :-)

    If the container doesn’t find a class implementing the needed interface, then, quite simply, nothing happens.

    Hope that makes sense.


  69. udidahan Says:

    Jeff,

    Jeremy Miller is using the event aggregator within a rich client application in order to loosen the coupling between UI/presentation logic. Domain events are designed to loosen the coupling between the domain model and other services (like sending email and whatnot).

    Hope that answers your question.


  70. udidahan Says:

    Jørn,

    Yeah – I do have a fairly large set of patterns that all work together in such a way that one’s strengths compensates for the others’ weaknesses.


  71. chloeqpc Says:

    I have this code working using Spring.NET IoC container, but I’m having trouble getting it working with Unity.

    Does anyone have a sample section from web/app.config that shows how to register classes that implement Handles ?

    I can get things working to the point where the container’s “Configure”
    method runs without errors, but the classes are not returned by ResolveAll.

    :(


  72. Bryan Prendergast Says:

    Udi, thanks. Yes, that makes sense.

    However, I still think a default may fit in certain cases. For instance, with my Validation scenario, perhaps, Customers have required fields but Orders do not. Then, my default case would be to always return true (valid). Thus, if Orders has NO required fields, it will simply always return true. However, this wouldn’t fit with your MakePreferred scenario . . . so maybe it’s an optional thing?


  73. udidahan Says:

    chloeqpc,

    I’m afraid that Unity requires some additional surrounding infrastructure to support this scenario. You can look at what’s been done in the NServiceBus source:

    https://nservicebus.svn.sourceforge.net/svnroot/nservicebus/trunk/src/impl/ObjectBuilder/ObjectBuilder.Unity

    Hope that helps.


  74. udidahan Says:

    Bryan,

    I’m not arguing that defaults don’t make sense in certain scenarios – and validation may well be one. The thing is that handling domain events (things that the domain has already stated are true) is a different kind of scenario, one where defaults don’t make as much sense.

    Hope that answers your question.


  75. Richard Dingwall » Using NUnit to check domain event handlers are registered Says:

    [...] been using Udi Dahan’s excellent Domain Events pattern in a project at work. It’s best to keep them as coarse-grained as possible, but we have [...]


  76. Jørn Wildt Says:

    I don’t know how much you know about Microsoft’s PRISM, but you might be interested in seeing how they manage publish/subscribe events in the UI – it’s much like what you have done here.

    See for instance the last 15 min. of the TechEd video here: http://www.ideablade.com/DevForceSilverlight/DevForceSilverlight_PrismExplorer.aspx?referer=cpeblast5 (a bit right of page center).


  77. udidahan Says:

    Jørn,

    I’m on the Prism Advisory Board, and was in close contact with the team. So, I guess the similarity has logical roots :-)


  78. Joe Says:

    Udi,

    In your original post (the 1st design) somebody was concerned about a failure event in a first domain method call not preventing a second domain method call. You responded by saying that only a single domain method call should be made because anything more means domain meaning has found it’s way into the service layer message handler.

    One of the problems Domain Events solves is getting domain related fault events out of the domain even in situations where entities may be deeply nested. What happens if a method is called on an aggregate root, it delegates to one of it’s underlying entities, the entity raises a fault event, and the aggregate root, not knowing a fault occurred, changes some of its state and returns? The changes to the aggregate root will be committed right? How do you protect against this type of situation?


  79. Chris Nicola Says:

    Udi I was wondering if something that uses IsAssignableFrom would make sense for the actions:

    public static void Raise(T args) where T: IDomainEvent {
    if (Container != null)
    foreach (var handler in Container.ResolveAll<IHandles>()) {
    handler.Handle(args);
    }
    if (_actions != null)
    foreach (var action in _actions) {
    if (action.GetType().IsAssignableFrom(typeof(Action)))
    ((Action) action)(args);
    }
    }


  80. udidahan Says:

    Chris,

    I’d suggest using IsAssignableFrom in scenarios where I don’t have the T as a generic parameter but as a type object (domainEventType) like so:

    if (typeof(Action<>).MakeGenericType(domainEventType).IsAssignableFrom(action.GetType())
    // do something

    Hope that answers your question.


  81. Chris Nicola Says:

    Thanks, second question, would you access nHibernate directly in a domain event handler? For example I have an event which adds a price to an investment each day:

    Investment.UpdatePrice(new Price());

    would be the action called that would lead to,

    DomainEvents.Raise(new UpdatedPriceEvent() {Investment = this, Price = newprice});

    Now in the handler for this event would it be sane for me to call nHibernate to query for a price for the same day to determine if I am adding a price for a day that is already in the database? Should this be done before calling UpdatePrice() instead?

    Thanks,
    Chris


  82. udidahan Says:

    Chris,

    That sounds like logic which should be in the domain itself to begin with. All in all, I’d say that a domain event handler shouldn’t really need to access NH either directly or indirectly.

    Hope that answers your question.


  83. David Nelson Says:

    This is an interesting and useful solution, although I am not entirely convinced yet. I have some of the same reservations that Giorgio (#45) has, although his argument is also not entirely convincing either. I will probably have to try it out for myself and see how it works.

    One question I have though is around transactions. Several other commenters, on this post and its predecessors, have raised the question about what to do if a transaction is rolled back after the domain event is raised. The answer has generally been that, given the assumption that the response to a domain event will be sending a message on a message bus, the bus’s transactional messaging system (e.g. MSMQ) will also roll back the messages. That works fine when you are only talking about communication between autonomous services. My question is what happens when there is no message bus or transactional messaging system involved? What happens when another component of the same client needs to know that a domain event has occurred, but only if the event is actually committed?

    For example, in our trading application, we have a workflow such that new orders arrive in a new state, and then a user acknowledges that order, which moves it to an active state. The user’s client needs to update the list of active orders when an order is acknowledged, as well as the count of active orders that is displayed in the status bar. I don’t want to explicitly update these other areas in the same code that handles the user input to acknowledge the order, as that starts leaking domain logic into the application service layer, and introduces additional coupling between these areas of the application. But I don’t want to depend on MSMQ for intra-application messaging just to get transactional messages. Any thoughts on how to solve this?


  84. udidahan Says:

    David,

    It sounds like you’ve got your answer – you just don’t like it :)

    > But I don’t want to depend on MSMQ for intra-application
    > messaging just to get transactional messages.

    It turns out that writing your own transactional messaging solution is far from a trivial endeavor. MSMQ is light-weight enough to be used inside an application – I’ve done it many times. When used with NServiceBus, you can get a fairly clean experience keeping much of the technology abstracted away.

    Hope that helps in some way.


  85. David Nelson Says:

    Udi,

    MSMQ may be light, but it comes with an administrative cost that I would rather not pay. Especially given that I don’t need the persistent guaranteed delivery that MSMQ is designed for. If the application crashes, I don’t care if the message never reaches is its destination, since the destination isn’t around anymore! Nor I do need the kind of transactional delivery that MSMQ provides, where a failed attempt to process a message results in the message being re-inserted in the front of the queue, and all of the fun locking issues that come along with that behavior.

    In fact, what I am looking for is not really transactional at all, it is merely gated. In other words, “when I send this message, don’t actually send it yet; wait until I say go.” Surely that can’t be so difficult? I guess I will just have to try it and see.


  86. Domain Events – Take 2 Says:

    [...] Update: The next post in this series is now online here. [...]


  87. Mohammad Azam Says:

    Hi Udi,

    Where do you register the domain events using the DomainEvents.Register method?


  88. udidahan Says:

    Mohammad,

    The domain event handlers are registered in the container, and then the domain event infrastructure uses the container to find the appropriate handlers.

    Does that answer your question?


  89. Mohammad Azam Says:

    Hi Udi,

    Thanks for the reply! Actually my question is regarding the following code:

    if (actions != null)
    foreach (var action in actions)
    if (action is Action)
    ((Action)action)(args);

    What is the difference between the above code and the following code:

    if (Container != null)
    foreach(var handler in Container.ResolveAll<Handles>())
    handler.Handle(args);

    I think Actions is used for domain events and Handle are being used for service oriented events like sending out emails etc.

    Is that correct or am I missing something?


  90. udidahan Says:

    Mohammad,

    The actions bit is really only there for testing purposes. There isn’t any practical difference between the two. Looks like it’s time to refactor that out to a different role.


  91. Joni Ben-Ami Says:

    Udi,

    I’ve been deliberating this methodology as an alternative to having the service layer manage processes that include both domain changes and persistence. This tends to make the domain anemic, but implementing an ORM and a messaging infrastructure are currently not options.

    But, following up on David’s post and your reply (#83,84), would you consider it correct to say that using Domain Events is really only proper if you have the kind of transactional messaging infrastructure that you are talking about (MSMQ)?


  92. Sam Says:

    Hello,
    Is it ok for domain events to contain data too?

    If I have ResultIsAvailable event, is it ok for it to have a Result property which the listener can access, or should domain events be used for sending messages only? i.e., should it be
    “A result is available and here it is”

    or just

    “A result is available.”

    I’d much prefer to use the former if it doesn’t raise any coupling issues.


  93. udidahan Says:

    Joni,

    Building a true domain model without having something like an ORM is possible, but you’d best forgo a relational persistence storage as well. Without an actual domain model, it isn’t entirely clear what kind of domain events would be raised.

    Even if you did have an ORM, the transactional behavior of processing a domain event would likely require some kind of transactional messaging infrastructure, not to mention other fault-tolerance scenarios which require it.

    On what was the decision not to use either of these in your project based?


  94. udidahan Says:

    Sam,

    Yes, domain events can contain data as well as references to domain objects.


  95. Joni Ben-Ami Says:

    Udi, the decision not to use an ORM essentially stems from lack of resources and conservativism. The project as a whole is relatively small and after some research, it seemed more time- and cost-efficient to build our own persistence framework. As for messaging, it has up until now been unnecessary, and the conservativism I mentioned implies minimal changes as well as minimal external components.

    But I will keep these things in mind next time I have an opportunity to implement them.


  96. udidahan Says:

    Joni,

    There’s never enough time to do it right, but there’s always enough time to do it again :)


  97. Jon Says:

    Udi, what happens when the domain event is reliant on some kind of infrastructure? For instance, what if I wanted to have a CustomerCreated domain event. I could raise the event in the constructor of the Customer entity, but typically a business doesnt see a Customer as Created until its actually been saved in the database.


  98. udidahan Says:

    Jon,

    See my post:

    http://www.udidahan.com/2009/06/29/dont-create-aggregate-roots/

    Does that answer your question?


  99. Think Before Coding Says:

    Manual trackback : Event sourcing and CQRS, now !
    http://thinkbeforecoding.com/post/2009/10/30/Event-Sourcing-and-CQRS-Now


  100. Angus McDonald Says:

    Udi,

    I’m trying to wire this up to try it out, but I can’t for the life of me work out what IContainer you are using. It looks like the one from NServiceBus 2.0 (with the extension method ResolveAll) but I’ve had a hard time bringing in references that make that work in my project.

    This means I can’t get this line of code to compile:
    foreach (var handler in Container.ResolveAll<Handles>())

    Any help would be appreciated!

    Thanks,
    Angus


  101. udidahan Says:

    Angus,

    Several containers support this out of the box, like Spring and Castle.

    Hope that helps.


  102. Simple Domain Events « BASICly everything Says:

    [...] pattern, so use at your own risk. A lot of this post was blatantly ripped off from inspired by Udi Dahan’s posts on the same subject. Other bits and pieces come from around the ‘net. Sorry I’m not giving credit. At the time, I [...]


  103. Jon Says:

    Udi,

    I’m still getting my head round how this will work. In your example, presumably your DoSomething() method would actually look like this:

    IsPreferred = true;
    DomainEvents.Raise(new CustomerBecamePreferred() { Customer = this });

    Suppose you have a handler that fires an email. What happens if the transaction in the service that calls the DoSomething() method fails (the database is down for instance)? Won’t the email still get sent even though the IsPreferred change was not persisted?

    Thanks, Jon


  104. udidahan Says:

    Jon,

    The handling of a domain event wouldn’t send the email directly, instead it would send a message using a bus to another endpoint, and that is the one that would send the email. That would provide for full transactional guarantees. You can look at NServiceBus for those kinds of bus capabilities.

    Does that answer your question?


  105. Josh Says:

    Could you answer Joe’s question from “September 3rd, 2009 at 9:47 am” when you get a chance?
    “In your original post (the 1st design) somebody was concerned about a failure event in a first domain method call not preventing a second domain method call. You responded by saying that only a single domain method call should be made because anything more means domain meaning has found it’s way into the service layer message handler.

    One of the problems Domain Events solves is getting domain related fault events out of the domain even in situations where entities may be deeply nested. What happens if a method is called on an aggregate root, it delegates to one of it’s underlying entities, the entity raises a fault event, and the aggregate root, not knowing a fault occurred, changes some of its state and returns? The changes to the aggregate root will be committed right? How do you protect against this type of situation?”


  106. udidahan Says:

    Josh,

    The point that you raise is an excellent one, and goes to the heart of designing domain models. It is the responsibility of the aggregate root that its state changes be in-sync with those of its collaborating entities.

    In short, the domain model is a tightly coupled set of classes that need to handle this. If they don’t, there’s nothing anybody can do from the outside to fix it.

    Designing a good domain model is hard, and ensuring that each aggregate root retains its logical consistency is one of those things that needs to be addressed.

    Sorry that there is no silver bullet for that one :)


  107. Advanced StructureMap: connecting implementations to open generic types - Jimmy Bogard - Los Techies : Blogs about software and anything tech! Says:

    [...] is an interface for domain events, where we’ll have handlers [...]


  108. Roger Says:

    What is this code snippet trying to do?

    30: if (actions != null)
    31: foreach (var action in actions)
    32: if (action is Action)
    33: ((Action)action)(args);

    Looks like it is trying to invoke a callback. But there is not invoke() function. If it is, do we still need to this? The domain event handler already sent the e-mail out.

    Thanks.


  109. DDDSample.NET 0.5, finally asynchronous! « Simon says… architecture! Says:

    [...] NHibernate. In this mode NHibernate is used to persist domain model data. Inter-aggregate communicaton is done synchronously using domain event pattern. [...]


  110. Julien Letrouit Says:

    Udi,

    Thanks for your great blog, you opened my eyes on so many subjects :) I have however a problem with this domain event dispatcher: every caller of domain logic that will trigger a given event must register the events themselves. So, the email will be sent when the customer become preferred only if all the methods in the service layer did not forget to register the event everywhere it might be raised.
    I would personally add a way to register handler types, so whenever an event occur, the compatible handlers will be instantiated and called, whether the service layer registered the event or not. Then only will be get the assurance the email is sent in every situation the customer becomes preferred.

    Or do I miss something?


  111. udidahan Says:

    Julien,

    Domain event handlers would be registered in the container at startup. Thus the service layer doesn’t have to register anything. The registering of an action callback is there primarily for testing purposes. Hope that clears it up for you.


  112. Julien Letrouit Says:

    Udi,

    oops, looks like I did not read the fine prints in details. Sorry for that.
    I tried to see if I could salvage all the calls to services in my domain using this design, and there are still a couple of places where I can’t see events to fit elegantly. For example, my User entity need a IEncodePassword (implementation is different from one customer to the other) when one of my user is changing his/her password. Would you still remove that service dependency from the User entity?

    Julien


  113. udidahan Says:

    Julien,

    Encoding a password sounds like functionality that isn’t very volatile – so you can probably implement it outside the domain model. You’ll probably have an in-memory dictionary of ClientID to EncodingStrategy, which you can look up in your service layer, encode, and then persist.

    Not everything needs to be done using a domain model :)


  114. David Henry Says:

    If domain events are occurring within a longer unit of work, then these should be registered with the unit of work so that they fire during the commit in case it is discarded, etc. In the previous articles, business rule failures were also included as events – however failure conditions might need to be raised as soon as they occur, and not necessarily be registered within the unit of work if no state change would occur.

    Should business rule failure events be a separate concept than the state change signifying domain events? To me, these failure events are notifications from the domain and are an expected part of state handling, not an exceptional case. It seems fitting to use a similar (if not the same) mechanism as the domain event handling for these, but seems to be blurring the intent.
    Thoughts?


  115. udidahan Says:

    David,

    I know that I showed the use of domain events for business rule failures in the previous post, the main reason being that it was something I knew would make sense to readers. The thing is that domain events aren’t meant to be used for that, quite simply because the domain model isn’t supposed to do validation (as I describe in my CQRS posts).

    Hope that answers your question.


  116. Steve Says:

    Udi,

    Was wondering what you thought about sending contextual data along with these events.

    For example, say I have an edit view for updating an entity. With this view the user is able to choose users to notify about the change. Following the example in the article the only data available when the actual handler method for this event is called would be data the entity knows about, which doesn’t include the users I want to notify. If I was blindly notifying all users this would not be an issue.

    My idea is to add an IContextualData property to IDomainEvent. So from the service layer it would be similar to this:

    public void UpdateEntityX(EntityUpdateRequest request){
    ‘ handle the request

    entity.WasUpdated(new EntityXUpdatedContextualData(…));
    ‘ where EntityXUpdatedContextualData implements IContextualData
    }

    in the domain entity:
    public void WasUpdated(IContextualData contextualData){
    events.Raise(new XWasUpdatedEvent(contextualData));
    }

    I see 2 capabilities this adds:
    1) The ability to send along any non-entity specific data I need the event handler to have, which could change depending on the context in which the event was fired.
    2) And the ability to use context-specific event handlers by adding a 2nd generic type parameter to IHandler for the type of contextual data being sent. (when X happens in the context of Y do Z)

    Obviously there are different ways to handle the situation I presented in the example, just wondering if there is anything bad architecturally about letting this contextual data hitch a ride on these events.

    Any thoughts?


  117. Strengthening your domain: Domain Events - Jimmy Bogard - Los Techies : Blogs about software and anything tech! Says:

    [...] Note that final sentence and the implied interaction.  When a fee as been paid off, the customer needs to be notified that to update their AtRisk flag.  Whenever we hear the word “When”, that should be a signal to us that there is a potential event in our system.  We would like to model this event explicitly in our system and to have our model reflect this kind of relationship between Fee and Customer.  In our case, we’re going to use a design from Udi Dahan, Domain Events. [...]


  118. udidahan Says:

    Steve,

    The scenario you’re describing seems to mix up different requirements – those of updates, and those of collaboration. At the very least, notification of other users can be identified as a different transaction than that of the update. As such, it isn’t appropriate to implement it as domain events on top of the first transaction.

    Hope that makes sense.


  119. Domain Events – Don’t observe us, we’ll observe you - db@net blog site Says:

    [...] discussion of how NServiceBus can assist in developing a domain events based application, read Udi Dahan’s article   RxFramework [...]


  120. Lars Says:

    Hi Udi,

    thank you for your great articles and software. One question:

    It seems that in your example, a domain event will be raised before calling tx.Commit(). Is this intentional? How will the subscribers/eventhandlers responsible for handling these events have access to the data, if they are potentially not committed to the database, for example?

    public void Handle(DoSomethingMessage msg)
    2: {
    3: using (ISession session = SessionFactory.OpenSession())
    4: using (ITransaction tx = session.BeginTransaction())
    5: {
    6: var c = session.Get(msg.CustomerId);

    //Event fired in DoSomething
    7: c.DoSomething();
    8:
    //Then a commit to the database
    9: tx.Commit();
    10: }
    11: }

    Could firing the events before data are committed lead to other inconsistencies, like a customer getting a mail “You are now a preferred customer”, but the transaction failed in a second method (doSomething2()) call done in the same context, and thus, the customer will not be updated in the database? Or am I missing something?


  121. udidahan Says:

    Lars,

    In previous comments (and in the post itself) I mentioned that any work done in the domain event handlers needed to be transactional as well. This means sending a message to an email-sending endpoint, rather than sending the email itself in the handler.

    Cheers.


  122. Lars Says:

    Thank you for your swift reply; I must be “screen blind” from reading way too many articles this weekend. :-)

    We are about to convert a rather large transaction script/anemic domain model application to something more up to date (and buzzword compatible :-) , and your ideas regarding CQRS and domain events are very tempting. The events make it easy to separate out secondary concerns from the primary business logic (registering order is pri #1, emailing and the customer is just a consequence of #1), while making it simple to find out where to hook those secondary requirements.


  123. Roy Oliver Says:

    Udi,

    Is it not true that the Infrastructure Layer should not reference the Domain Layer? The Domain Layer sits above the Infrastructure Layer.

    Being the case, I’m still unclear as to what fits where. I know professionals like you hate to talk about full implementation because that is the developer’s call, but something more.

    Could we talk about this in terms of assemblies?

    Say I have:
    Project.Domain
    Project.Infrastructure

    Say I have an event called, “CustomerNameChanged”. So a Customer object calls a method that changes the customer’s name. Within the method, the CustomerNameChanged event is Raised and later handled by the CustomerNameChangedHandler.

    You mentioned that event handlers (e.g., CustomerNameChangedHandler) do not belong in the domain, so that means they belong in the Infrastructure (right?). So CustomerNameChangedHandler goes somewhere in Project.Infrastructure. Being that CustomerNameChanged is a domain event, it goes somewhere in Project.Domain (right?). Yet if the handler is in the Infrastructure Layer, which sits below the Domain Layer, that means the Infrastructure would need to reference the Domain in order to handle the CustomerNameChanged event.

    Love the concept, but still confused


  124. Roy Oliver Says:

    Correction:

    Being the case, I’m still unclear as to what fits where. I know professionals like you hate to talk about full implementation because that is the developer’s call, but {I need} something more.


  125. udidahan Says:

    Roy,

    The domain event handlers can be thought of as being *beside* the service layer in that they will use the bus to push out messages, but are still separate from the service layer.

    I suggest reading about CQRS which introduces packaging which has more dimensions than the one-dimensional layering.


  126. Stu Says:

    Hi,

    I have a problem that I’ve explained on Stack Overflow. Basically I have a situation where neither double dispatch or domain events seem to fit properly. Does anyone have any suggestions?

    http://stackoverflow.com/questions/3148853/service-behaviour-in-entity-how-to-avoid-service-injection-into-entity


  127. Stan Says:

    What if my Customer class is not sealed and it have some inheriting children (for example private and business customer) and my business logic demands different handling for CustomerBecomePrefered event for different types of customers?
    How than I handle that event?
    Thanks.


  128. Jonas Kello Says:

    Udi, do you think it would be a good practise to use Domain Events to update the Presentation Model state of a smart client?

    For example, lets say we have an order entry app with a Silverlight client and there are several ViewModels displayed in a complex shell. Some (more than one) ViewModels would have to update some data (to change red, green, yellow images etc) when the the status of the order they represent changes. Now lets say that one ViewModel sends a command to the server which causes a domain event of type OrderStatusChanged to occur. Could we have all the status-dependent ViewModels subscribe directly to OrderStusChangedEvent to make them update?

    Also if this is a good idea, then how would you suggest propagating the domain events down to the client-side?


  129. udidahan Says:

    Stan,

    In that case, it sounds like it is likely that the thing that raised the CustomerBecamePreferred event would also be aware of the different types of customers, thus I’d argue it should handle the differences in business logic between the two, and not subscribers to the domain event.


  130. Rasmus Christensen Says:

    Hi Udi,

    Great easy to read article, again. Would this fit into a hosted web app? I think in terms of CQRS?


  131. udidahan Says:

    Rasmus,

    Since the domain events are ultimately raised in-memory, there’s no reason why it wouldn’t work in a hosted web app environment.


  132. Maninder Says:

    Udi, i can see the value of representing “what” happened within domain as an event(s), but i was wondering if events can be used as input to domain model? For example, a person takes an action on a web UI, should it be modelled as an event that describes the intention of the end user?
    I see following choices
    1. Pass primitive data types to the service method. the bits in the parameters represent the data entered by a user on UI screen
    2. Pass a generic dto
    3. Pass an intention revealing event.
    If i go by step 3, then my application will have input events, output events, system events etc.
    Am i over engineering ? What are your thoughts?


  133. udidahan Says:

    Maninder,

    Actions from the UI are modeled as intention-revealing commands – not events. These commands indicate what is desired, but the system may ultimately reject. Events represent something that already happened.

    You might want to read my posts on CQRS for information about this:

    http://www.udidahan.com/2009/12/09/clarified-cqrs


  134. kenshin Says:

    Sorry for the double entry … I’m reposting this due to typos in the previous one

    I don’t quite understand why should we use the code you presented in your article unless we want to build an EventManager from scratch. Seems to me that this is equivalent to using a message bus from within the domain object every time there is a need to raise an event, something similar to

    jmsService.send(destination, message)

    jmsService would be equivalent to DomainEvents

    Am I missing something ?

    Thank you


  135. udidahan Says:

    Kenshin,

    If you’ve noticed in my later blog posts, I’ve mentioned how many domain models may ultimately end up as long-running processes (aka sagas) in which case the events raised are indeed published using a message/service bus.


  136. kenshin Says:

    Udi,
    Which blog post you’re referring to, is it “Don’t Create Aggregate Roots” ? Are you saying that if we’re not dealing with long-running processes, we should resort to only an event manager ? is that necessarily ligther than using a message bus.

    Thank you
    kenshin


  137. udidahan Says:

    Kenshin,

    Don’t take each of these blog posts as a full architectural picture – these are designed to nudge people in a certain direction. There are so many ways that people abuse domain models that the goal is to get them to see a different perspective.


  138. Nuno Lopes Says:

    This might be a bit of a late question. But shouldn’t domain events be handled after the transaction ends?

    Is there any specific reason for handle domain events within the same transaction scoping DoSomething?

    Nuno


  139. udidahan Says:

    Nuno,

    Domain events get handled by service layer objects in the same process which usually send out other messages – as such, we want those messages to be sent (or not) in the same transactional context.


  140. Jason Says:

    I have scanned the 139 postings in response to this article, and have not seen this questions asked. Please forgive me if I missed it.

    I am seriously looking at CQRS in combination with all the other DDD goodies. In particular Event sourcing.

    My question is, given the separation between commands (things you want to happen) and events, what actually happened. If you were building a framework to give the ability to reverse/replay/compensate. In an event, would you record the full state of the object, before/after, both or only what changed with before/after or simply what changed after.

    I am specifically lookin at this from the reverse/replay/compensate and audit trail point of view.

    Compensate is something I have added. For situations such as you have reverved a hotel room via a Gateway to another system and your transaction fails, thus you need to compensate for the failure with a system that is not in your transaction boundary.

    I have already implemented recording commands, and am wondering if you would also record events, and if so, exactly what you would record.


  141. Jason Says:

    A separate question.

    On comand/event separation. Is it not equally valid to say

    A customer requested a change to their address as it is to say A customer requests a change to their address.

    My reasoning is by the time it gets to your domain model, it is in the past.


  142. udidahan Says:

    Jason,

    I’m not very positive about the benefits of event sourcing so I’m not sure I’m in a position to answer your questions. One reason is that I don’t think that the majority of raw data in the system (like customer first name, last name, phone numbers, etc) actually need to be in the domain model when doing CQRS.


  143. Mark Lee Says:

    I’m trying to get my head around DDD (and so far loving what it has to offer), and I’m wondering if Domain Events are an appropriate method to communicate between Bounded Contexts.

    I am developing a web-ordering system, where submitted orders are sent to a remote web service (controlled by another part of the business). I’m thinking of two primary bounded contexts: Local and Remote (actual names are more appropriate to the business context, but just keeping things simple here). When an order is saved in the Local context, I’ve been thinking about using Domain events to trigger the order being submitted in the Remote context to the web service.

    Does a domain event seem like the right approach in this case? And, more generally, does communicating between bounded contexts using domain events seem reasonable?


  144. udidahan Says:

    Mark,

    Yes, domain events are a useful way to keep to BCs in sync. The specific scenario you’re raising (calling a web service) is one where you’d probably be better off by introducing messaging between your BCs so that the non-deterministic latency of the web service call doesn’t end up slowing down your system.


  145. Dan Says:

    Udi,

    In message number 120 above, Lars asks about how to access the data if the event is fired before the commit. I didn’t understand your response. Maybe my situation is different so I’ll explain.

    I have 2 BCs. One context deals with the merging of employee information. I’d like to fire a domain event specifying that the employee was merged. I’d like the 2nd BC to react to this event. The issue is that the data won’t be committed at that point, and this data that changed is vital to the 2nd BC to react.

    Am I going down the wrong path by attempting to use domain events? Is there another solution you could suggest?


  146. udidahan Says:

    Dan,

    The question is whether you need both your BCs to be consistent with each other at *all* times – ergo in the same transaction.

    If the answer is yes, then you absolutely do want the event to be raised and handled in the same transaction – you’d also be deploying both BCs together.

    If the answer is no, then you should use some kind of message bus between the BCs. The handler for the domain event would publish a message using the bus, and that would be enlisted in the same transaction – thus is the first BC rolled back, the message wouldn’t be sent. The second BC would be invoked by the bus when the message arrives at its queue where its handling would then be done in a separate transaction.


  147. Dan Says:

    Udi,

    Thank you for taking the time to answer my question. After some thought I’m having difficulty determing if the *need* to be consistent. I’m using NHibernate as my persistence mechanism. I’ve wrapped NHibernate’s ISession in a custom UnitOfWork class.

    My application service does the following:

    using(IUnitOfWork uow = UnitOfWork.Create())
    {
    IRepository repository = ….

    Driver driver = repository.GetById(driverIdToMerge);

    driver.Merge(driverId);

    uow.PersistAll();
    }

    My probem is that I can’t have the domain events actually be raised until the session is flushed and all commands have been sent to the database because the 2nd BC involved expects those changes to be there.

    What I’ve done is this. I’ve taken your DomainEvents class and added some functionality to essentially store all the events it has been sent from the domain objects. When PersistAll() is called above it starts a transaction, flushes the session and commits the changes.
    Then within the same method it raises all of the events in the DomainEvents class by calling a static method named RaiseAll(). This currently works because the changes have been committed and the 2nd BC can act appropriately.

    I don’t like the way this is implemented. It doesn’t hurt anything if the 2nd BC is executed, it just doesn’t make any sense for it to. I’d like the entire thing to run under one transaction if possible.

    Now, finally for my question. The only way I see to have the seperate BC’s be executed under the same transaction is if I pass the session into the handler. Is this OK to do? Something about this just doesn’t seem right. Thanks again for your help.


  148. udidahan Says:

    Dan,

    I’d be quite suspicious about BCs that always need to be consistent with each other – this high temporal coupling indicates that there is a strong semantic coupling as well.


  149. Dan Says:

    I was a bit worried about this while designing this behavior in a seperate BC. Everything made sense to be in a different BC until I came across this last part. It appears I’m going to have to reevaluate what I’ve done and bring the two together.


  150. Jason Says:

    I’m trying to implement a forums system where Forum has a list of Topics which have a list of Posts. In my current model, I have top-down one-way relationships (i.e. Posts don’t know which Topic they’re in & Topics don’t know which Forum they’re in).

    When a new post is added to a topic or a new topic is added to a forum, I’d like to cache some summary information (last post title for a topic/forum, last poster for a topic, total topics, total replies per thread and forum, etc.). I initially thought about caching these in the parent object, but I’m leaning more towards having new entities for ForumMetrics and TopicMetrics that get updated when a DomainEvent is fired from the containing object.

    However, reading through the comments above, it seems you’re suggesting staying away from calling into repositories from DomainEvent handlers. Do you have a suggestion for how I might persist this summary information otherwise?


  151. udidahan Says:

    Jason,

    Those metrics don’t need to be handled in the same transaction as the new post or topic, right? In which case, I’d recommend sending a message from your domain event handler to another endpoint, and it will be the one doing those calculations.


  152. Jason Says:

    Thanks Udi. I don’t suppose they need to be in the same transaction, but ideally they would be. I guess not hearing you arguing against the entity relationships is also helpful too (metrics didn’t seem like they belonged on the forum/thread/post objects). Can you suggest what sending to another endpoint might look like when I’m not using a message bus? This is just a fairly straightforward single instance ASP.NET MVC app.


  153. udidahan Says:

    Jason,

    Keeping the metrics in a different persistent object model is a good idea. Sending to another endpoint is something that you would do using something like NServiceBus – ergo a multi-process solution.

    You could shortcut this somewhat by having the other endpoint be hosted in a separate appdomain in the same process – would that help?


  154. Robert Stackhouse (@rstackhouse) Says:

    Udi, I really like Domain Events concept. After reading your post and several others (http://elegantcode.com/2010/01/06/event-driven-architecture-publishing-events-using-an-ioc-container/ and http://trycatchfail.com/blog/post/Heavy-controller-actions-The-Message-Bus-Pattern-to-the-rescue!.aspx for example), it feels like I basically have two options:

    Create an application server as you suggest (not really sure what that would look like; NT Service perhaps?) to get around the ThreadStatic problem in ASP.NET

    OR

    Move the responsibility of publishing events outside of the domain (for example: in an MVC controller, as is done in the two articles I linked to above).

    Are there any other approaches which you are aware that I might be missing?

    If there aren’t any other options, are you aware of any good resources on creating an application server?

    I’ve read quite a few blogs on CQRS recently, but the technique seems ephemeral at best at this point.


  155. udidahan Says:

    Robert,

    You can use NServiceBus to create an application server – see the async pages sample for an example of how this would look.


  156. Byron Sommardahl Says:

    I’m REALLY late to the game, but I thought it would still be okay to interject. I really like the idea of domain events to help bring behavior to a domain model. But, the static domain event invoker has always bothered me. I’m such a nerd, that it kept me up all night thinking through an alternative that works just as well, is easily testable (without blurring the lines between unit test and integration test… my main problem with the use of static), and is expressive and elegant. I came up with something that I think it worth a look. https://github.com/bsommardahl/DomainEvents

    This implementation uses plain ole .NET events and handlers. I included a sample project to show how it works. I also wrote up some documentation to help you get started.

    This implementation is in production on a few projects already and it works very well.

    By the way, Udi, your article on Domain Events has been very inspirational. For me, it’s where the light bulb went off for this concept.


  157. Byron Sommardahl Says:

    By “light bulb went off”, I mean “light bulb came on”… good ole Tennessee english. :)


  158. udidahan Says:

    Byron,

    We’re going to providing support for domain events with NServiceBus, seeing as the handling side is so similar to message handling.

    Other than that, I like your approach of providing access through a field.


  159. Life without distributed transactions Says:

    [...] together in your domain model. You might be using some kind of event model (like I wrote about here) to percolate out the information that an entity was created in order to keep your service layer [...]


  160. cdpena Says:

    “CustomerBecamePreferred is nothing at all like IEmailService.”

    That clinches it.


  161. Ludwig Says:

    What about the following solution… domain entities don’t have any dependencies, so don’t use repositories, and are manually created (not dependency injected). However, they should be able to raise events. So what may be possible it to make every domain entity inherit from a base class that has a way to set an IDomainEventRegistrator. The IDomainEventRegistrator would have an operation like ‘RaiseEventAfterCommit’ that is used inside the domain entity, which just queues a domain event. This queue is kept in the unit of work (or the data context), and after a commit all domain events are dispatched to the correct event handler. If a domain entity is created in the application layer, it’s easy to provide an instance of the IDomainEventRegistrator to the entity (via the constructor, for example). When the entity is materialized from the database by entity framework code first, you can use the ObjectMaterialized event in the data context to set the IDomainEventRegistrator instance. This way domain entities only have a dependency on the IDomainEventRegistrator, which has a simple implementation: contains only a list of domain events and an operation to add an event.


  162. Paul Says:

    Really, really, … , really annoyed that I didn’t read this 4 years ago.

    Then again, maybe it would have been lost on me then.

    This post answered a lot of questions for me. Thanks


  163. Domain Events pattern single point to queue events | BlogoSfera Says:

    [...] using the answer below and some info from here: http://www.udidahan.com/2009/06/14/domain-events-salvation/ I came up with the following but it’s not quite [...]


  164. rh Says:

    Hi,

    This is the same sort of example I keep reading everywhere, and it is great, but none of them ever answers a question I’m dying to figure out.

    In an event driven architecture like this, it is considered an advantage that no matter where the event is being raised it will always work, which is great, but then to stick with this concrete example, you raise a domain event when a customer becomes preferred, which will trigger an email being sent, which is what you expect, but what happens when suddenly there is one use-case where this is not required? (Let’s say an employee is making a number of customers preferred internally in a bulk, and only internals want one email of the whole list when the procedure ends). If you fire your event in your domain which you will use to make customers preferred, that event will fire and trigger emails being sent one by one, how do you get around that for this ONE specific use-case where all the others need that email?


  165. Peter Dalinis Says:

    http://pdalinis.blogspot.com/2013/05/taking-domain-events-up-notch.html

    My most recent implementation.


  166. udidahan Says:

    rh,

    A situation like that would probably be handled by a slightly different system deployment. What I mean by that is that the CustomerBecamePreferredEventHandler that sends emails wouldn’t be deployed to that system.

    Of course, there are numerous other ways to handle this, some of which probably lean on a specific batch command that may go through a different domain model that doesn’t raise the same events.

    Hope that helps.


  167. Jan Kronquist Says:

    Instead of using a static method call to raise the events I prefer to use simple return values, ie return the domain events from the command handler and let the application service raise the events. This makes it even easier to test and much easier to explain. Have a look at my recent blog post:

    http://www.jayway.com/2013/06/20/dont-publish-domain-events-return-them/

    What do you think?


  168. udidahan Says:

    Part of the purpose of the event-based model was so that the top-most object that is invoked does not need to be aware of what other objects it invokes do / which events they’d want to raise.

    You’d lose that with return values.


  169. Jan Kronquist Says:

    Sure, there might be complex cases where you generate events in lots of different places. However, is this the most common case?

    My point is that most cases are simpler and then using return values would be easier to understand. In the few complex cases nothing is preventing you from using a static resource to collect events then return them, something like:

    public List performSomething(params) {
    EventRaiser.assertIsEmpty();
    // all your logic goes here
    return EventRaiser.collect();
    }

    … or perhaps use a different return value to indicate to the caller that they need to collect events elsewhere.


  170. udidahan Says:

    Jan,

    I’d say that many of the simple cases don’t warrant a domain model at all, let alone events.


  171. rh Says:

    Udi,

    Thanks for the answer regarding my question, yes it helped, also, I know it is way too late (better late than never I guess) I watched your presentations from the ddd exchange in 2010 and 2011 and they helped me a lot to understand (or realize that I misunderstood) a lot of things regarding aggregates, and a bunch of other things. However one thing puzzles me and I hope you can still clarify it regarding domain events. Namely you say that domain events are not there to inform you that “somethign was created, or updated”, instead they should tell cover what else to do (in the ship order cancel order example), like your “InvokeCancellationFee” event. This though, goes aginst most things I have read about domain events stating that they should actually mean that something happened (already) and they should be in past tense, etc. which does not really applicable to your explanation.
    Was this just because CQRS in the picture? is that more of a command sort of event? (in that case why not just contructing an aggregate that could handle that as well? maybe bacause invoking a fee like that resides in a different bc and you are messaging to that?)

    Thanks


  172. udidahan Says:

    rh,

    With regards to this statement:

    “Namely you say that domain events are not there to inform you that “somethign was created, or updated”, instead they should tell cover what else to do”

    I wouldn’t say that *at all*.

    Events always tell you what happened, but my recommendation is to stay away from CRUD-centric structures and to focus on business-oriented occurrences.

    InvokeCancellationFee would be a command that could be sent by a domain event handler.

    If you can give me a link to what you’re referring to, maybe I’ll be able to shed some more light on it.


  173. rh Says:

    Hi Udi,

    Thanks for the quick answer,

    here’s the link of your presentation back in 2010:

    http://skillsmatter.com/podcast/design-architecture/architectural-innovation-cqrs

    The part I am referring to is from 46 min to 48 min, and on the presentation it is mostly page 14/18

    Regards


  174. udidahan Says:

    rh,

    By golly, you’re right – I did say that in that presentation. I should have shown the full solution instead of that “shortcut”.

    The domain event should have been ShippedOrderCancelled, and the handler should have sent the InvokeCancellationFee command.


  175. rh Says:

    Udi,

    Thanks for the clarification, that was the only part of that presentation that I just could not place, no matter how hard I tried :)
    What you are saying in your comment makes it all fit, thanks again

    Regards


  176. Rock Johnson Says:

    Udi,

    Can a simple implementation of the event aggregator pattern serve the same role and purpose as your implementation of the domain event pattern?


  177. fabson Says:

    please do you have a simple working code to show how this pattern is utilized. i copied the code to vs2012 and it was complaining about the conainer.resolveall which i changed to GetAllInstances , dont know wether thats right, i think if i can get a working sample it will help. cant figure out what glues this whole thing together


  178. Oğuzhan Says:

    When I was using Transaction perrequest:

    Example:
    - Client renamed a card from ui (RenamedCardCommand)
    - RenamedCardCommand find Card aggregate and call Rename method
    - Rename method Raise CardRenamedEvent
    - CardRenamedEventHandler handle CardRenamedEvent and publish changed card name to all online users (SignalR)
    - Transaction commit

    When transaction was failure, all clients already notified new card name.

    Should EventHandlers handle event in same transaction or after the success transaction in new transaction block?

    Thanks,


  179. udidahan Says:

    Oğuzhan,

    The problem you have is that you aren’t using the correct transaction scope. What you need to do is to send the RenameCardCommand message using a service bus such that when it’s processed, you get stronger transaction support.

    Also, you’d want the publishing of the CardRenamedEvent to also be done via a service bus rather than in-memory – that way you get a single transaction around the processing of the command and the publishing of the event.

    Then you’d have your web tier subscribe to that CardRenamedEvent using the service bus and then have it use SignalR to broadcast that to the browsers.

    Cheers.


  180. Arvin Says:

    Hi Udi,

    Correct me if I’m wrong, the DomainEvents is located in the domain right? and the IContainer is an IoC?

    Isn’t the Domain Model supposed to be free of implementation or infrastructure?


  181. udidahan Says:

    The DomainEvents infrastructure is accessible from “the domain” but isn’t part of it. IContainer is indeed an IoC.

    With regards to the domain model being free from dependencies on infrastructure – you could say that we’re compensating for missing capabilities in the programming language or runtime. Everything is built on something.


  182. Kijana Woodard Says:

    @Arvin -
    To Udi’s point on #181, is “throw” part of the domain?

    If we were programming in Erlang, or even F#, we wouldn’t think to ask this question.


  183. Mike P. Says:

    Hello Udi,
    Great post!

    I am wondering how you would use domain events to return data back from an Service API

    Result DoSomething(string customerId)
    {
    customer = customerRepository.Get(customerId)
    return customer.DoSomething();
    }

    Considering DoSomething will fire an event, and the work will be processed in an event handler… how do you return the results of the work? or is this not a good use of domain events


  184. udidahan Says:

    Hi Mike,

    I wouldn’t recommend using domain events for the purpose of a return value. Domain events are there to state what *else* was performed, in addition to the work already requested.


  185. Daniil Says:

    Hi Udi,

    Very useful and helpful article series, many thanks!

    I have some thoughts here, could you please comment them?

    1) As far as i can see there is two methods of callback registration – DomainEvents.Register and handler registration in IoC.
    What is the benefit of such dualism? After all, it seems that IoC handlers aren’t cleaned up on ClearCallbacks function, so we can’t rely on ClearCallbacks…
    After first read i thought that the Register is ONLY for tests, but phrase “When used server side, please make sure that you add a call to ClearCallbacks in your infrastructure’s…” made me quite messy.

    It leads us to inconsistent events state since we have to think twice – call ClearCallbacks and erase IoC, isn’t it?

    2) Also, i am interesting in the arguments against direct events declarations on Domain Entities.
    Why don’t we declare entity like described below?

    public class Customer{
    public DomainEvent SomethingChangedEvent;
    public DoSomething(){
    DomainEvent.Raise(this);
    }
    }

    //as described in previou article
    public class DomainEvent
    {

    //but with little addiction
    DomainEvents.Raise(this);
    }

    //where DomainEvents will only work with IoC without direct events registration?

    I am not sure that what I’ve written is correct, but this allows us to bind on concrete entity event as well as on all events across application through IoC for some general purposes.

    Anyway, thanks for the great work!


  186. Daniil Says:

    sure, it should be SomethingChangedEvent.Raise(this) instead of DomainEvent.Raise(this) in the code


  187. Ali Shahzad Says:

    Hi Udi,

    I’m using the v5 nsb binaries with default container.

    1) I had to make some changes to the Raise method in DomainEvents.cs, in order to compile the code. this is because ResolveAll is not part of the public methods (anymore?). So it looks like that:
    if (Container != null)
    foreach (var handler in Container.BuildAll(typeof(IHandleDomainEvent)))
    ((IHandleDomainEvent)handler).Handle(args);

    2) I’m able to compile, but i get a Null reference exception at runtime- Container is not been DI’ed I guess.

    Is it something new in v5 or am i missing something?


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

Bryan Wheeler, Director Platform Development at msnbc.com
Udi Dahan is the real deal.

We brought him on site to give our development staff the 5-day “Advanced Distributed System Design” training. The course profoundly changed our understanding and approach to SOA and distributed systems.

Consider some of the evidence: 1. Months later, developers still make allusions to concepts learned in the course nearly every day 2. One of our developers went home and made her husband (a developer at another company) sign up for the course at a subsequent date/venue 3. Based on what we learned, we’ve made constant improvements to our architecture that have helped us to adapt to our ever changing business domain at scale and speed If you have the opportunity to receive the training, you will make a substantial paradigm shift.

If I were to do the whole thing over again, I’d start the week by playing the clip from the Matrix where Morpheus offers Neo the choice between the red and blue pills. Once you make the intellectual leap, you’ll never look at distributed systems the same way.

Beyond the training, we were able to spend some time with Udi discussing issues unique to our business domain. Because Udi is a rare combination of a big picture thinker and a low level doer, he can quickly hone in on various issues and quickly make good (if not startling) recommendations to help solve tough technical issues.” November 11, 2010

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."

Shy Cohen Shy Cohen, Senior Program Manager at Microsoft
“Udi is a world renowned software architect and speaker. I met Udi at a conference that we were both speaking at, and immediately recognized his keen insight and razor-sharp intellect. Our shared passion for SOA and the advancement of its practice launched a discussion that lasted into the small hours of the night.
It was evident through that discussion that Udi is one of the most knowledgeable people in the SOA space. It was also clear why – Udi does not settle for mediocrity, and seeks to fully understand (or define) the logic and principles behind things.
Humble yet uncompromising, Udi is a pleasure to interact with.”

Glenn Block Glenn Block, Senior Program Manager - WCF at Microsoft
“I have known Udi for many years having attended his workshops and having several personal interactions including working with him when we were building our Composite Application Guidance in patterns & practices. What impresses me about Udi is his deep insight into how to address business problems through sound architecture. Backed by many years of building mission critical real world distributed systems it is no wonder that Udi is the best at what he does. When customers have deep issues with their system design, I point them Udi's way.”

Karl Wannenmacher Karl Wannenmacher, Senior Lead Expert at Frequentis AG
“I have been following Udi’s blog and podcasts since 2007. I’m convinced that he is one of the most knowledgeable and experienced people in the field of SOA, EDA and large scale systems.
Udi helped Frequentis to design a major subsystem of a large mission critical system with a nationwide deployment based on NServiceBus. It was impressive to see how he took the initial architecture and turned it upside down leading to a very flexible and scalable yet simple system without knowing the details of the business domain. I highly recommend consulting with Udi when it comes to large scale mission critical systems in any domain.”

Simon Segal Simon Segal, Independent Consultant
“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).”

Ward Bell Ward Bell, VP Product Development at IdeaBlade
“Everyone will tell you how smart and knowledgable Udi is ... and they are oh-so-right. Let me add that Udi is a smart LISTENER. He's always calibrating what he has to offer with your needs and your experience ... looking for the fit. He has strongly held views ... and the ability to temper them with the nuances of the situation.
I trust Udi to tell me what I need to hear, even if I don't want to hear it, ... in a way that I can hear it. That's a rare skill to go along with his command and intelligence.”

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.”

Catherine Hole Catherine Hole, Senior Project Manager at the Norwegian Health Network
“My colleagues and I have spent five interesting days with Udi - diving into the many aspects of SOA. Udi has shown impressive abilities of understanding organizational challenges, and has brought the business perspective into our way of looking at services. He has an excellent understanding of the many layers from business at the top to the technical infrstructure at the bottom. He is a great listener, and manages to simplify challenges in a way that is understandable both for developers and CEOs, and all the specialists in between.”

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.”

Neil Robbins Neil Robbins, Applications Architect at Brit Insurance
“Having followed Udi's blog and other writings for a number of years I attended Udi's two day course on 'Loosely Coupled Messaging with NServiceBus' at SkillsMatter, London.

I would strongly recommend this course to anyone with an interest in how to develop IT systems which provide immediate and future fitness for purpose. An influential and innovative thought leader and practitioner in his field, Udi demonstrates and shares a phenomenally in depth knowledge that proves his position as one of the premier experts in his field globally.

The course has enhanced my knowledge and skills in ways that I am able to immediately apply to provide benefits to my employer. Additionally though I will be able to build upon what I learned in my 2 days with Udi and have no doubt that it will only enhance my future career.

I cannot recommend Udi, and his courses, highly enough.”

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.”

Børge Hansen Børge Hansen, Architect Advisor at Microsoft
“Udi delivered a 5 hour long workshop on SOA for aspiring architects in Norway. While keeping everyone awake and excited Udi gave us some great insights and really delivered on making complex software challenges simple. Truly the software simplist.”

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 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!”

Chris Bilson Chris Bilson, Developer at Russell Investment Group
“I had the pleasure of attending a workshop Udi led at the Seattle ALT.NET conference in February 2009. I have been reading Udi's articles and listening to his podcasts for a long time and have always looked to him as a source of advice on software architecture.
When I actually met him and talked to him I was even more impressed. Not only is Udi an extremely likable person, he's got that rare gift of being able to explain complex concepts and ideas in a way that is easy to understand.
All the attendees of the workshop greatly appreciate the time he spent with us and the amazing insights into service oriented architecture he shared with us.”

Alexey Shestialtynov Alexey Shestialtynov, Senior .Net Developer at Candidate Manager
“I met Udi at Candidate Manager where he was brought in part-time as a consultant to help the company make its flagship product more scalable. For me, even after 30 years in software development, working with Udi was a great learning experience. I simply love his fresh ideas and architecture insights.
As we all know it is not enough to be armed with best tools and technologies to be successful in software - there is still human factor involved. When, as it happens, the project got in trouble, management asked Udi to step into a leadership role and bring it back on track. This he did in the span of a month. I can only wish that things had been done this way from the very beginning.
I look forward to working with Udi again in the future.”

Christopher Bennage Christopher Bennage, President at Blue Spire Consulting, Inc.
“My company was hired to be the primary development team for a large scale and highly distributed application. Since these are not necessarily everyday requirements, we wanted to bring in some additional expertise. We chose Udi because of his blogging, podcasting, and speaking. We asked him to to review our architectural strategy as well as the overall viability of project.
I was very impressed, as Udi demonstrated a broad understanding of the sorts of problems we would face. His advice was honest and unbiased and very pragmatic. Whenever I questioned him on particular points, he was able to backup his opinion with real life examples. I was also impressed with his clarity and precision. He was very careful to untangle the meaning of words that might be overloaded or otherwise confusing. While Udi's hourly rate may not be the cheapest, the ROI is undoubtedly a deal. I would highly recommend consulting with Udi.”

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.”

Ian Cooper Ian Cooper, Team Lead at Beazley
“Udi is one of the leaders in the .Net development community, one of the truly smart guys who do not just get best architectural practice well enough to educate others but drives innovation. Udi consistently challenges my thinking in ways that make me better at what I do.”

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.”

Adam Dymitruk Adam Dymitruk, Director of IT at Apara Systems
“I met Udi for the first time at DevTeach in Montreal back in early 2007. While Udi is usually involved in SOA subjects, his knowledge spans all of a software development company's concerns. I would not hesitate to recommend Udi for any company that needs excellent leadership, mentoring, problem solving, application of patterns, implementation of methodologies and straight out solution development.
There are very few people in the world that are as dedicated to their craft as Udi is to his. At ALT.NET Seattle, Udi explained many core ideas about SOA. The team that I brought with me found his workshop and other talks the highlight of the event and provided the most value to us and our organization. I am thrilled to have the opportunity to recommend him.”

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.”


Carl Kenne Carl Kenne, .Net Consultant at Dotway AB
“Udi's session "DDD in Enterprise apps" was truly an eye opener. Udi has a great ability to explain complex enterprise designs in a very comprehensive and inspiring way. I've seen several sessions on both DDD and SOA in the past, but Udi puts it in a completly new perspective and makes us understand what it's all really about. If you ever have a chance to see any of Udi's sessions in the future, take it!”

Avi Nehama, R&D Project Manager at Retalix
“Not only that Udi is a briliant software architecture consultant, he also has remarkable abilities to present complex ideas in a simple and concise manner, and...
always with a smile. Udi is indeed a top-league professional!”

Ben Scheirman Ben Scheirman, Lead Developer at CenterPoint Energy
“Udi is one of those rare people who not only deeply understands SOA and domain driven design, but also eloquently conveys that in an easy to grasp way. He is patient, polite, and easy to talk to. I'm extremely glad I came to his workshop on SOA.”

Scott C. Reynolds Scott C. Reynolds, Director of Software Engineering at CBLPath
“Udi is consistently advancing the state of thought in software architecture, service orientation, and domain modeling.
His mastery of the technologies and techniques is second to none, but he pairs that with a singular ability to listen and communicate effectively with all parties, technical and non, to help people arrive at context-appropriate solutions. Every time I have worked with Udi, or attended a talk of his, or just had a conversation with him I have come away from it enriched with new understanding about the ideas discussed.”

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.”

Rhys Campbell Rhys Campbell, Owner at Artemis West
“For many years I have been following the works of Udi. His explanation of often complex design and architectural concepts are so cleanly broken down that even the most junior of architects can begin to understand these concepts. These concepts however tend to typify the "real world" problems we face daily so even the most experienced software expert will find himself in an "Aha!" moment when following Udi teachings.
It was a pleasure to finally meet Udi in Seattle Alt.Net OpenSpaces 2008, where I was pleasantly surprised at how down-to-earth and approachable he was. His depth and breadth of software knowledge also became apparent when discussion with his peers quickly dove deep in to the problems we current face. If given the opportunity to work with or recommend Udi I would quickly take that chance. When I think .Net Architecture, I think Udi.”

Sverre Hundeide Sverre Hundeide, Senior Consultant at Objectware
“Udi had been hired to present the third LEAP master class in Oslo. He is an well known international expert on enterprise software architecture and design, and is the author of the open source messaging framework nServiceBus. The entire class was based on discussion and interaction with the audience, and the only Power Point slide used was the one showing the agenda.
He started out with sketching a naive traditional n-tier application (big ball of mud), and based on suggestions from the audience we explored different solutions which might improve the solution. Whatever suggestions we threw at him, he always had a thoroughly considered answer describing pros and cons with the suggested solution. He obviously has a lot of experience with real world enterprise SOA applications.”

Raphaël Wouters Raphaël Wouters, Owner/Managing Partner at Medinternals
“I attended Udi's excellent course 'Advanced Distributed System Design with SOA and DDD' at Skillsmatter. Few people can truly claim such a high skill and expertise level, present it using a pragmatic, concrete no-nonsense approach and still stay reachable.”

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!

Jose Manuel Beas
“When I attended Udi's SOA Workshop, then it suddenly changed my view of what Service Oriented Architectures were all about. Udi explained complex concepts very clearly and created a very productive discussion environment where all the attendees could learn a lot. I strongly recommend hiring Udi.”

Daniel Jin Daniel Jin, Senior Lead Developer at PJM Interconnection
“Udi is one of the top SOA guru in the .NET space. He is always eager to help others by sharing his knowledge and experiences. His blog articles often offer deep insights and is a invaluable resource. I highly recommend him.”

Pasi Taive Pasi Taive, Chief Architect at Tieto
“I attended both of Udi's "UI Composition Key to SOA Success" and "DDD in Enterprise Apps" sessions and they were exceptionally good. I will definitely participate in his sessions again. Udi is a great presenter and has the ability to explain complex issues in a manner that everyone understands.”

Eran Sagi, Software Architect at HP
“So far, I heard about Service Oriented architecture all over. Everyone mentions it – the big buzz word. But, when I actually asked someone for what does it really mean, no one managed to give me a complete satisfied answer. Finally in his excellent course “Advanced Distributed Systems”, I got the answers I was looking for. Udi went over the different motivations (principles) of Services Oriented, explained them well one by one, and showed how each one could be technically addressed using NService bus. In his course, Udi also explain the way of thinking when coming to design a Service Oriented system. What are the questions you need to ask yourself in order to shape your system, place the logic in the right places for best Service Oriented system.

I would recommend this course for any architect or developer who deals with distributed system, but not only. In my work we do not have a real distributed system, but one PC which host both the UI application and the different services inside, all communicating via WCF. I found that many of the architecture principles and motivations of SOA apply for our system as well. Enough that you have SW partitioned into components and most of the principles becomes relevant to you as well. Bottom line – an excellent course recommended to any SW Architect, or any developer dealing with distributed system.”

Consult with Udi

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

97 Things Every Software Architect Should Know



Creative Commons License  © Copyright 2005-2011, Udi Dahan. email@UdiDahan.com    Freely hosted by Weblogs.us