Skip to content

Question about Approach 10 - Aggregates with MediatR Events #5

@opcodewriter

Description

@opcodewriter

Isn't an issue that the Product domain model has public c-tors which do not check for the validity of the name?
This makes it possible to have an invalid Product model.

    public class Product
    {
        public Product()
        {
        }
        public Product(string name)
        {
            Name = name;
        }

        ....
   }

https://github.com/ardalis/DDD-NoDuplicates/blob/master/NoDuplicatesDesigns/10_AggregateWithMediatR/Product.cs

I'm not sure what's the solution for this. Maybe make the Product c-tors private and add a factory method and a new domain event, something like this:

public class Product 
{
       private Product()
       {
       }
       private Product(string name)
       {
           Name = name;
       }

      public static Product Create(int catalogId, string name)
      {
             DomainEvents.Raise(new ProductCreationRequested(catalogId, name)).GetAwaiter().GetResult();
             return new Product(name);
      }
}

Add add the new event handler class inside the Catalog class:

public class ProductCreationHandler : INotificationHandler<ProductCreationRequested>
{
    public Task Handle(ProductCreationRequested notification, CancellationToken cancellationToken)
    {
        var catalog = _catalogRepository.GetById(notification.CatalogId);
        catalog.AddProduct(notification.Name); // AddProduct(catalogId, name) would be private in the Catalog class
        
        return Task.CompletedTask;
    }
}

What do you think?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions