Mohsen
Mohsen

Reputation: 4266

DDD Can I use abstract factory to create domain objects

I have a domain model which has some Abstract Entities with some Concrete Entities to add extensibility .

I can add some Base app service which can accept an Abstract Factory and Abstract Repository to apply the shared logic between concrete entities .

The question:

1 . Am I in a true road?

2 . if yes , How should I inject the factory into the service?

Upvotes: 1

Views: 604

Answers (1)

Zoran Horvat
Zoran Horvat

Reputation: 11301

You can inject factory to an entity if it is not possible to resolve the concrete object immediately. Factories are useful when their product can only be instantiated later, for example because data it expects are not ready yet.

So yes, you can inject concrete factory to an entity, and Dependency injection is the right way to do that.

On a related note, there is one very specific scenario, which also affects DDD. This might not be your actual situation, but it's worth mentioning. It could happen that the decision which concrete product to produce is part of the domain logic. I mean, selection of the factory is not fixed, but depends on concrete situation in terms of the domain logic.

In that case, I sometimes choose to add part of the domain logic to the concrete factory implementation. The result is that abstract factory is defined in the same way as before, but concrete factory becomes part of the domain model. That is somewhat unusual and needs to be done carefully. There is the analysis of this approach in Switchable Factory Methods and Domain Logic in Factories.

Upvotes: 1

Related Questions