Sam Gentile, Independent WCF & SOA Expert
“Udi, one of the great minds in this area.
A man I respect immensely.”
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, 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.”
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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, .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, 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, 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, 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, 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, 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, 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, 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, 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.”
Consult with Udi
June 14th, 2009 at 2:46 am
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.
June 14th, 2009 at 2:52 am
Domain Events – Salvation – Udi Dahan…
Thank you for submitting this cool story – Trackback from DotNetShoutout…
June 14th, 2009 at 4:35 am
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?
June 14th, 2009 at 4:45 am
Szymon,
Glad that it was helpful.
June 14th, 2009 at 4:49 am
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?
June 14th, 2009 at 4:59 am
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.
June 14th, 2009 at 5:03 am
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!)?
June 14th, 2009 at 5:07 am
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.
June 14th, 2009 at 5:41 am
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?
June 14th, 2009 at 6:16 am
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?
June 14th, 2009 at 6:19 am
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?
June 14th, 2009 at 6:21 am
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
June 14th, 2009 at 6:24 am
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
June 14th, 2009 at 9:06 am
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
June 14th, 2009 at 10:54 am
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.
June 14th, 2009 at 1:52 pm
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…)
June 14th, 2009 at 11:17 pm
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…
June 15th, 2009 at 12:33 am
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
June 15th, 2009 at 7:23 am
Udi,
Watch out on that [ThreadStatic] attribute–it can bite you hard in ASP.NET:
http://bit.ly/6CWZl
June 15th, 2009 at 8:05 am
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
June 15th, 2009 at 10:37 pm
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.
June 15th, 2009 at 10:54 pm
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.
June 16th, 2009 at 3:50 am
When is the handler “registered”? Am I missing something?
June 16th, 2009 at 5:38 am
Eb,
The handler would be registered in the container at application startup.
Does that make sense?
June 16th, 2009 at 10:22 am
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.
June 16th, 2009 at 11:54 pm
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.
June 18th, 2009 at 7:06 am
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
June 18th, 2009 at 1:50 pm
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…
June 20th, 2009 at 11:58 am
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.
June 20th, 2009 at 12:03 pm
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
June 20th, 2009 at 3:34 pm
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.
June 21st, 2009 at 1:19 am
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?
June 21st, 2009 at 5:56 pm
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
June 23rd, 2009 at 12:13 pm
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.
June 25th, 2009 at 2:50 am
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)?
June 25th, 2009 at 5:42 am
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?
June 25th, 2009 at 5:46 am
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?
June 25th, 2009 at 7:14 am
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!)
June 25th, 2009 at 8:32 am
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.
June 25th, 2009 at 8:50 am
Udi
Aha – I was missing that! It makes sense now.
Thanks again
Sean
June 29th, 2009 at 5:52 am
[...] previous post on Domain Events left some questions about how aggregate roots should be created unanswered. It would actually be [...]
July 1st, 2009 at 1:01 pm
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?
July 7th, 2009 at 6:59 am
[...] Dahan has two excellent posts about domain events and the creation of aggregate [...]
July 27th, 2009 at 9:57 pm
[...] the past few weeks, both Udi Dahan and Jeremy D. Miller have posted on events. Udi posted about domain events, while Jeremy posted [...]
July 31st, 2009 at 7:19 am
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.
July 31st, 2009 at 11:02 am
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?
August 1st, 2009 at 12:02 am
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
August 1st, 2009 at 11:18 am
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.
August 1st, 2009 at 11:21 am
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.
August 1st, 2009 at 11:22 am
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.
August 1st, 2009 at 11:25 am
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?
August 3rd, 2009 at 11:58 am
[...] ‘Domain Events – Salvation’ by Udi [...]
August 3rd, 2009 at 4:58 pm
“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
August 3rd, 2009 at 11:08 pm
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.
August 5th, 2009 at 1:09 pm
[...] 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 [...]
August 5th, 2009 at 8:15 pm
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
August 6th, 2009 at 12:18 am
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?
August 10th, 2009 at 1:01 pm
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
August 12th, 2009 at 7:51 am
Jørn,
It sounds like you’ve pretty much answered yourself
August 12th, 2009 at 5:00 pm
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??
August 13th, 2009 at 11:22 pm
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
August 14th, 2009 at 1:22 pm
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
August 14th, 2009 at 1:29 pm
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.
August 14th, 2009 at 2:12 pm
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 . . .
August 16th, 2009 at 8:19 pm
Udi, how is your approach different from Jeremy Miller’s Event Aggregator?
Would be cool if you could comment on non-container specific details.
August 17th, 2009 at 5:56 am
@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.
August 18th, 2009 at 11:34 am
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.
August 19th, 2009 at 9:28 am
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.
August 19th, 2009 at 9:30 am
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.
August 19th, 2009 at 9:33 am
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.
August 26th, 2009 at 12:48 pm
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.
August 26th, 2009 at 2:09 pm
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?
August 29th, 2009 at 1:16 pm
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.
August 29th, 2009 at 1:18 pm
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.
August 30th, 2009 at 6:31 pm
[...] 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 [...]
September 1st, 2009 at 6:55 am
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).
September 1st, 2009 at 10:25 am
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
September 3rd, 2009 at 9:47 am
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?
September 10th, 2009 at 4:33 pm
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);
}
}
September 10th, 2009 at 9:11 pm
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.
September 14th, 2009 at 9:44 am
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
September 14th, 2009 at 11:12 am
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.
September 16th, 2009 at 12:37 pm
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?
September 20th, 2009 at 2:51 am
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.
September 22nd, 2009 at 8:04 am
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.
October 11th, 2009 at 2:50 am
[...] Update: The next post in this series is now online here. [...]
October 11th, 2009 at 10:28 am
Hi Udi,
Where do you register the domain events using the DomainEvents.Register method?
October 11th, 2009 at 12:36 pm
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?
October 12th, 2009 at 11:23 am
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?
October 12th, 2009 at 12:06 pm
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.
October 21st, 2009 at 2:34 pm
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)?
October 22nd, 2009 at 3:34 pm
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.
October 24th, 2009 at 1:37 am
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?
October 24th, 2009 at 1:38 am
Sam,
Yes, domain events can contain data as well as references to domain objects.
October 24th, 2009 at 5:16 am
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.
October 24th, 2009 at 9:16 am
Joni,
There’s never enough time to do it right, but there’s always enough time to do it again
October 29th, 2009 at 11:01 am
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.
October 29th, 2009 at 3:25 pm
Jon,
See my post:
http://www.udidahan.com/2009/06/29/dont-create-aggregate-roots/
Does that answer your question?
October 30th, 2009 at 7:55 am
Manual trackback : Event sourcing and CQRS, now !
http://thinkbeforecoding.com/post/2009/10/30/Event-Sourcing-and-CQRS-Now
November 8th, 2009 at 5:24 pm
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
November 14th, 2009 at 7:22 am
Angus,
Several containers support this out of the box, like Spring and Castle.
Hope that helps.
November 15th, 2009 at 6:20 am
[...] 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 [...]
December 1st, 2009 at 11:18 am
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
December 1st, 2009 at 8:43 pm
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?
December 10th, 2009 at 1:21 pm
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?”
December 12th, 2009 at 8:31 am
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
December 17th, 2009 at 8:40 pm
[...] is an interface for domain events, where we’ll have handlers [...]
January 3rd, 2010 at 2:57 pm
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.
January 21st, 2010 at 7:00 am
[...] NHibernate. In this mode NHibernate is used to persist domain model data. Inter-aggregate communicaton is done synchronously using domain event pattern. [...]
February 22nd, 2010 at 5:04 pm
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?
February 23rd, 2010 at 10:30 am
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.
February 25th, 2010 at 1:10 pm
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
February 28th, 2010 at 8:29 am
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
March 25th, 2010 at 10:00 am
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?
March 28th, 2010 at 2:44 pm
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.
March 30th, 2010 at 10:08 am
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?
April 8th, 2010 at 12:55 pm
[...] 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. [...]
April 11th, 2010 at 10:42 am
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.
April 12th, 2010 at 10:20 am
[...] discussion of how NServiceBus can assist in developing a domain events based application, read Udi Dahan’s article RxFramework [...]
May 2nd, 2010 at 4:05 pm
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?
May 3rd, 2010 at 7:09 am
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.
May 3rd, 2010 at 12:37 pm
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.
May 21st, 2010 at 4:46 pm
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
May 21st, 2010 at 4:50 pm
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.
May 29th, 2010 at 8:54 pm
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.
June 30th, 2010 at 7:07 am
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
July 18th, 2010 at 9:47 am
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.