views:

606

answers:

3

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.

+2  A: 

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.

David Kemp
+2  A: 

I've seen a couple of ways to do this.

The most common way is to use dependency injection to inject the repositories into the objects that use them. Usually these are presenter or controller classes but in some cases the model calls into the repository. Usually it's better if you avoid this. If you can use a di-container to do this then go for it.

You can also make the repositories implement the singleton pattern. I'd try to avoid this because singletons usually use static methods. This can make testing the code that calls into the singletons more difficult. If you have to do things this way then make sure you separate out the code that calls the singleton and use "manual" dependency injection to inject the singletons into the classes that call them. This gets rid of some of the tight coupling you'd otherwise get.

I've seen some examples where the repositories never get called. When someone navigates the object graph in the model and requests an object that isnt loaded the model just raises an event and the repository reacts to this event. This way there are no calls into the repository and it's completely decoupled from the model. I havn't used this architecture myself but it seems very clean.

Mendelt
A: 

I am not sure about this and I have the same problem. I think that you should make a repository a singleton when the objects that it works with are used often. And that it shouldn't be made a singleton if you use objects that it works with rarely, because the repository would take a lot of memory for objects and maybe it would be called only once and never again during usage of the application. As I said, this may not be correct thinking.

gljivar