Search code examples
clean-architectureardalis-cleanarchitecture

How to a raise a domain event for the entity when the entity is created in clean architecture


I have a project created using the clean architecture template.

If I want a domain event be raised when a new project is created, where do I add that?

If I have to raise an event whenever a new item be added to a project, I can accomplish that in the Project entity as shown here.

Similarly for MarkCompletion of a ToDoItem as done here.

But its not clear where do I put the code to raise an event when a new Project is created?

One option is doing something like the following in Create End Point here.

    newProject.Events.Add(new ProjectCreatedEvent(newProject));

But this is in UI, away from the domain model, and so does not feel right.

The other option is using ef core interceptors. So when ever save changes is called, just raise event as appropriate something like here.

And if I add event in Project ctor, then this is triggered even in case of an update.

      public Project(string name)
      {
        Name = Guard.Against.NullOrEmpty(name, nameof(name));
        
        var newProjectCreatedEvent = new NewProjectCreatedEvent(this);
        
        Events.Add(newProjectCreatedEvent);
      }

Are there any better options/patterns?

Any pointer is deeply appreciated.


Solution

  • When you need to raise a domain event on project creation I would create a factory method that publishes the event.

    You can use a static method or implement a factory object.

    
    public class Project : BaseEntity, IAggregateRoot
    {
        public static Project newProject(string name)
        {
            var project = new Project(name);
            
            var newProjectCreatedEvent = new NewProjectCreatedEvent(project);
        
            Events.Add(newProjectCreatedEvent);
            return project;
        }
    
        private Project(string name)
        {
          Name = Guard.Against.NullOrEmpty(name, nameof(name));
        }
    }