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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With