Skip to content

Where to use events

Jon P Smith edited this page Sep 14, 2020 · 2 revisions

Most of your business logic will be written as normal services that are called, like CreateOrder. Events are useful when doing one thing as an effect that isn't obviously linked to the business logic you would run. For instance

  • Creating an Order triggers a check on reorder more Stock.
  • Setting/changing an Address triggers a recalculation of the sale tax code of a Job.
  • Updating a Book trigger an update of book’s Projection on another database.
  • Receiving a Payment that pays off the debt triggers the close of the Account.

Each example has two entity class names in italic, and these entity classes are not directly linked to each other: Order/Stock, Address/Job, Book/Projection, Payment/Account. That gives you an idea as to when you might use events, that is when one action kicks off another action which isn’t directly linked to the first action. Conversely events aren’t useful when the entity classes are already closely linked, for instance you wouldn’t use events to set up each LineItem in an Order because they are very much linked to each other.

Another place where events can be useful is when you want to add a new feature to some already written code. If you don’t want to alter the already set up methods and business logic you might be able to add a new feature using events. A good example of this is shown in my article A technique for building high-performance databases with EF Core where I improved the performance of a working web app. That means I didn’t have to change the existing services and front-end code of the web app, but I triggered events when properties/methods in the entity class changed. That ensured that any change that altered the cached values were caught and an event handler was run to update the specific cache value.

Clone this wiki locally