Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DDD repositories as singletons?

Tags:

Quick question: Would it be a good or a bad idea to implement my domain-driven design style repositories as singletons? Why?

Or should I maybe use a dependency injector container to manage my repositories and decide if they are singletons or not?

I'm still reading DDD Quickly, and would like to see some good repository examples.

like image 399
Torbjørn Avatar asked Nov 27 '08 15:11

Torbjørn


People also ask

Should repository be a singleton?

Don't use static or singleton repositories because of: It affects testablility, you can not mock it when unit testing. It affects extensibility, you can not make more than one concrete implementation and you can not replace behavior without re-compiling.

What is DDD Repository pattern?

The Repository Pattern has gained quite a bit of popularity since it was first introduced as a part of Domain-Driven Design in 2004. Essentially, it provides an abstraction of data, so that your application can work with a simple abstraction that has an interface approximating that of a collection.


1 Answers

Use your dependency injection container to decide how and where repositories are created.

By using

UserRepository.Instance.Find(userId);

you're creating a barrier to testing.

If your repositories are passed into services using Constructor Injection, then you can also easily replace them with mocks.

like image 185
kͩeͣmͮpͥ ͩ Avatar answered Sep 19 '22 21:09

kͩeͣmͮpͥ ͩ