Domain Services
are necessary when you have a Domain Model because there is functionality that's not a part of your entities.
Think for example about a Repository
or a Factory
. The interface for a Repository
will probably be in your Domain Layer
but the implementation in your Infrastructure Layer
. With a Factory
, both the implementation and interface will be in your Domain Layer
.
These Domain Services are used from your Application Layer. The goal of an application layer is to make sure that everything is in place so the Domain Model can do his work. This could mean loading specific entities from Repositories and then calling domain specific functions on them.
Validation should go inside an Entity. For example, lets suppose you have a Money
class.
public class Money
{
public Money(string currency, int amount)
{
Currency = currency;
Amount = amount;
}
public int Amount { get; set; }
public string Currency { get; set; }
}
If the Money
class is not allowed to have a negative amount, where would you validate this?
The best place to do this is inside the class. An entity is responsible for its own state.
In a Money
class, this is easy to see but for example with an Order
class with OrderLines
the Order
is responsible for checking if there are duplicate OrderLine
items that should be merged (saves shipping costs!)