tlt
tlt

Reputation: 15221

Is injecting repository in aggregate root / entity considered bad design?

I am trying to learn about details of domain driven design and i came to this question. I found many examples with:

  1. Defining repository interface within the domain
  2. Defining repository implementation somewhere else
  3. Inject repository interface into aggregate root

On the other hand, there are examples that strictly go against it and do all repository related stuff from service.

I cannot find authoritive answer and explanation: is it considered a bad practice and if so - why?

Upvotes: 2

Views: 1401

Answers (1)

VoiceOfUnreason
VoiceOfUnreason

Reputation: 57249

I cannot find authoritive answer and explanation: is it considered a bad practice and if so - why?

Yes, mostly because a number of different concerns get confused.

Aggregates define a consistency boundary; any change of state should be restricted to a collection of related entities that are all part of the same aggregate. So once you have looked up the first one (the "root" entity), you should be able to achieve the change without needing to examine any data other than this graph of domain entities and the arguments that you have been passed.

Put another way, Repository is a plumbing concern, not a domain concern. Your domain entities are responsible for expressing your domain, without infrastructure concerns getting mixed in.

To have, for example, Aggregate.Save() method that would inside use IRepository interface to save.

Aggregate.Save() definitely indicates a problem. Well, two problems, to be precise: Save probably isn't part of your ubiquitous language, and for that matter its likely that Aggregate isn't either.

Save isn't a domain concern, it's a persistence concern - it just copies data from your in memory representation (volatile storage) to a durable representation (stable storage). Your domain model shouldn't need to know anything about that.

One of the reasons you found "many examples with" is that getting these concerns separated correctly is hard; meaning you really need to think deeply about the problem to tease them apart. Most examples don't, because teasing things apart isn't critical when you always deploy everything together.

Upvotes: 8

Related Questions