DI and Singleton Pattern in one implementation

I want to reorganize some code using the Windsor IOC / DI infrastructure, but my problem is that I have some Singleton classes and Factory template classes, and I'm not sure if Singleton or Factory can be implemented using DI.

Are there any ideas if possible and how?

+6
c # inversion-of-control
source share
3 answers

The Singleton design pattern is not consistent with DI. Although it is possible to open Singleton so much that DI and the Open / Closed Principle begin to make sense, this will greatly change Singleton, it almost ceases to be Singleton.

Thread safety is one big issue that comes to mind when you start opening Singleton.

It is much better to simply define your services and classes without considering too many of their capabilities. If you have an object that you would like to share among multiple consumers, most DI containers have a Singleton lifetime concept that mimics the benefits of the Singleton design pattern without suffering from any flaws.

In short, singleton are evil and should be avoided.

Abstract Factory , on the other hand, is very useful for DI purposes.

+6
source share

You do not do this, you allow the IOC container to do this. If you used to have explicit calls to factory to get an instance of a single object, now you have an IOC container to create a graph of objects for you, and it intercepts everything where it belongs. The container ensures that your singletones are single, and it acts like a factory.

If you say that at runtime the factory decide which object should be serviced, DI is not applicable there, except that you can use the DI container, factory where you want, and manage it for you.

+2
source share

Most modern dependency injection frameworks allow you to specify whether they should serve an instance of a single object for the life of the application (or request) or create new instances each time you request it.

You can also use the DI framework to resolve dependencies in factories when appropriate (if that's what you mean). You can do this if the factory selects a subclass based on the runtime data, or if the dependent object needs to create multiple IFoo instances, in which case you can enter IFooFactory .

0
source share

All Articles