Search code examples
.netarchitecturedomain-driven-designdto

How can i call DTO in domain layer if it must be implemented on application layer?


I'm developing a project with .NET and I'm trying to implement DDD design with onion architecture. I read some articles and my understanding was: the application layer must contain the DTOs and the domain layer must contain the services (only the ones responsible for business rules). That said, let's get to the problem: In my domain services, I can't import my DTOs because it's in the application layer and my domain layer can't import anything from there. How can I resolve this? Did I build it wrong or in the wrong order? Code I'm trying to write:

Task SetCategories(List<SetCategoriesRequest> categories);

The error:

The type or namespace name 'type/namespace' could not be found (are you missing a using directive or an assembly reference?)


Solution

  • the domain layer must contain the services

    And the models used by those services. For example, in the code shown there is a semantic concept of a "category". If this entity is part of the business domain then that domain would contain a class which models this entity. Any domain-specific, technology-agnostic attributes and aspects of that semantic concept would be included in that domain model.

    The application layer and infrastructure layer(s) can reference the domain and use its models, but the domain should not reference the other layers.

    So for example in a web application you might have controller actions which invoke business operations related to a "category". Those controller actions can directly use that model where it makes sense to do so.

    In the event that any given layer needs to re-shape the data for purposes specific to that layer (view models for specific UI interactions, DTOs for interacting with external web services, etc.) those layers can also define their own DTOs for that purpose. Any conversion between the domain models and the layer-specific DTOs would happen in that layer.

    When interacting with the domain, that interaction would use domain models. So in this case if SetCategories is a domain operation which is performed on a collection of "categories" then it would expect a collection of Category domain models (or perhaps some aggregate domain model which contains a collection of Category domain models), not an application layer DTO.