'DDD why should domain model define interfaces for infrastructure

While studying DDD I'm wondering why the Domain model need to define interfaces for the Infrastructure layer.

From my reads I got that a high level (domain model, application service, domain service) defines interfaces that need to be implemented by a lower layer (infrastructure). Simple.

From this idea I think it makes sense that an application level (in a high level) defines interfaces for a lower one (infrastructure) because the application level will use infrastructure components (A repository is a usual client of the applicaiton layer) but doesn't want to be tied to any special implementation.

However, this is confusing when I see in some books a domain level defining infrastructure interfaces because a domain model will not use ever a repository because we want our domain model "pure".

Am I missing something?



Solution 1:[1]

While studying DDD I'm wondering why the Domain model need to define interfaces for the Infrastructure layer.

It doesn't really -- that's part of the point.

The domain model defines the interfaces / contracts that it needs to do work, with the promise of happily working with any implementation that conforms to the contract.

So you can choose to implement the interface in your application component, or in the infrastructure component, or where ever makes sense.

Note the shift in language from "layer" to "component". Layers may be too simplistic to work -- see Udi Dahan 2007.

Solution 2:[2]

I came across the same question myself. From my understanding, the reason behind this is that you want the application to only consume objects/interfaces defined in the Domain Model. It also helps to keep one repository per aggregate since they sit next to each other in the same layer.

The fact that the Application layer has a reference to the Infrastructure layer is only for the purpose of dependency injection. Your Application layer services should call these interfaces exposed in the Domain layer, get Domain Objects (POCOs), do things and possibly call interfaces again; for example to commit a transaction. This is why for example the Unit of Work pattern exposes its action through a Domain Layer interface.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 VoiceOfUnreason
Solution 2 Ama