DDD-NoDuplicates icon indicating copy to clipboard operation
DDD-NoDuplicates copied to clipboard

Question about Approach 10 - Aggregates with MediatR Events

Open opcodewriter opened this issue 3 years ago • 1 comments

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?

opcodewriter avatar May 21 '21 10:05 opcodewriter

2nd question: By taking a dependency on the MediatR, isn't considered a hidden dependency?

opcodewriter avatar May 22 '21 13:05 opcodewriter