How can I use the repository pattern correctly?

One thing that I did wrong when playing around with repository pattern—just like you, I thought that table relates to repository 1:1. When we apply some rules from domain-driven design, the grouping repositories problem often disappears.

The repository should be per the Aggregate root and not table. It means, if entity shouldn’t live alone (i.e., if you have a Registrant that participates in a particular Registration), it’s just an entity, and it doesn’t need a repository. It should be updated/created/retrieved through the repository of aggregate root it belongs to.

Of course, in many cases, this technique of reducing the count of repositories (actually, it’s more a technique to structure your domain model) can’t be applied, because every entity is supposed to be an aggregate root (that highly depends on your domain, I can provide blind guesses only). In your example, License seems to be an aggregate root, because you need to be able to check them without any context of the Registration entity.

But that does not restrict us to cascade repositories (the Registration repository is allowed to reference the License repository if needed). That does not restrict us to reference the License repository (preferable, through IoC) directly from the Registration object.

Just try not to drive your design through complications provided by technologies or misunderstanding something. Grouping repositories in ServiceX just because you don’t want to construct two repositories isn’t good idea.

Much better would be to give it a proper, name, RegistrationService, for example.

But services should be avoided in general. They often are cause that leads to an anemic domain model.

Do start to use IoC. It truly eases the pain of injecting dependencies.

Instead of writing:

var registrationService = new RegistrationService(new RegistrationRepository(),
      new LicenseRepository(), new GodOnlyKnowsWhatElseThatServiceNeeds());

you will be able to write:

var registrationService = IoC.Resolve<IRegistrationService>();

P.S.: It would be better to use so called common service locator, but that’s just an example.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)