I read .NET Domain-Driven Design with C#: Problem – Design – Solution and I noticed that the author created a domain service for each aggregate root.
However, the domain services were only facades to the corresponding repository. For example this is a code sample from the application from his book
public static class CompanyService
{
private static ICompanyRepository repository;
private static IUnitOfWork unitOfWork;
static CompanyService()
{
CompanyService.unitOfWork = new UnitOfWork();
CompanyService.repository =
RepositoryFactory.GetRepository<ICompanyRepository,
Company>(CompanyService.unitOfWork);
}
public static IList<Company> GetOwners()
{
return CompanyService.GetAllCompanies();
}
public static IList<Company> GetAllCompanies()
{
return CompanyService.repository.FindAll();
}
public static void SaveCompany(Company company)
{
CompanyService.repository[company.Key] = company;
CompanyService.unitOfWork.Commit();
}
public static Company GetCompany(object companyKey)
{
return CompanyService.repository.FindBy(companyKey);
}
}
As you see almost all calls to the services are wrappers to repository calls. Is this a good pattern when building domain services?
Should we always wrap our repositories in domain services? Is there a better approach?
4
A repository is meant to be an abstraction for your data store, and generally provides data-retrieval capabilities. This arrangement allows you to, for example, change out the data store for some different datastore (say, from Oracle to SQL Server, although in practice this rarely happens), and your repository API should still work, if you didn’t expose any implementation-specific details.
A service layer, on the other hand, is an API meant to be consumed by some outside user or agent, and provides services, not data retrieval per se (although it can do that). A Service API might draw on multiple repositories, and perform transforms on the data before serving it to the client. It might wrap the data into custom objects, or provide paging abilities. You can do things in your service layer beyond simple data storage and retrieval.
If you don’t have the need to provide an additional layer of abstraction beyond what your Repository provides, you might not need a Service Layer at all.
2
As your application grows, there are complex operations that your service layer can wrap and expose. It’s really a facade over the domain model. For instance in a sales app, you might not care about the line item as a discrete object within the model. You just want to add items to a cart, check them out, and print an invoice for the user after any discounts are applied.
Behind the scenes there are probably dozens of objects involved in the interaction. The service might project a flattened view of the object model so that as the domain model changes behind the scenes, the client is not impacted by those changes.