-
Notifications
You must be signed in to change notification settings - Fork 12
Where to use events
There are two questions for the where to use events:
- Which type of events are used where?
- When will a event be more useful than a simple update?
- The Before events (also knows as domain events) are the most used. These allow you to add extra changes to the data being written out to the database.
- The During events (also knows as integration events) are used when you want to link two systems. Your data is saved to the application's database within an transaction before you During event(s) is called. If any During event returns an error (or exception), then the update to your application's database is rolled back and an error/exception is returned.
- The After events are only run if the SaveChanges / SaveChangesAsync was successful. They are useful for say sending an email or invalidating a cached value once you are sure the update worked.
Most of your business logic will be written as normal services that are called, like CreateOrder and won't use events. But events are useful for two situations
Here are some examples
- 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.
If you don’t want to alter the already set up methods and business logic you might consider adding events to implement a new feature that is very different to what is there already. 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.