C# Domain-Driven Design – Implementing Interfaces in Domain Entities

cdomain-driven-design

Please see the question here: https://stackoverflow.com/questions/2352654/should-domain-entities-be-exposed-as-interfaces-or-as-plain-objects

The general consensus is that Domain Models should not contain interfaces. Now see here: https://github.com/jbogard/presentations/blob/master/WickedDomainModels/After/Model/Member.cs and specifically this code:

public Offer AssignOffer(OfferType offerType, IOfferValueCalculator valueCalculator) 
        { 
            DateTime dateExpiring = offerType.CalculateExpirationDate(); 
            int value = valueCalculator.CalculateValue(this, offerType); 


            var offer = new Offer(this, offerType, dateExpiring, value); 


            _assignedOffers.Add(offer); 


            NumberOfActiveOffers++; 


            return offer; 
        } 

The author if this blog writes a lot about DDD.

Notice that an interface is injected into the method here instead of a concrete type i.e. IOfferValueCalculator implements OfferValueCalculator.

I am talking from the perspective of a DDD purist. Is it acceptable for domain entities to implement interfaces? If the answer is yes, then in what circumstances would it be acceptable to inject an IOfferCalculator into a Domain Entity: Member?

Once again I realise that the DDD approach is not a one size fits all and that an Anemic Domain model is suitable in a lot of cases. I am just trying to improve my knowledge of this specific area.

Best Answer

IOfferValueCalculator is not a domain entity. It is a service. So it is perfectly fine for it to be an interface.

And there is some nuance in the "Should entities implement interfaces" question. While it is true that creating interface only for it to be implemented by single entity is useless complexity. There is nothing wrong with multiple entities implementing single interface, as those entities might be interchangeably used in code, that runs same logic on all of entities.