简体   繁体   中英

DI and Singleton Pattern in one implementation

I want to refactor some code using the Windsor IOC/DI framework, but my issue is that I have some Singleton classes and Factory pattern classes and I am not sure that one can implement a Singleton or Factory using DI.

Has anyone any ideas if that is possible and how?

The Singleton design pattern is at odds with DI. While it's possible to open up a Singleton so much that DI and the Open/Closed Principle starts to make sense, this will change the Singleton so much that it almost stops being a Singleton.

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

It's much better to simply define your services and classes without considering their scope too much. If you have an object that you would like to share between multiple consumers, most DI Containers have the concept of a Singleton lifetime , which mimics the benefits of the Singleton design pattern without suffering from any of the drawbacks.

In short: Singletons are evil and should be avoided.

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

You don't, you let the IOC container do it. Where before you had explicit calls to a factory to get a singleton instance of an object, now you have the IOC container create a graph of objects for you, and it hooks everything up where it belongs. The container makes sure your singletons are singletons, and it acts as the factory.

If you are talking about having a factory decide at runtime what kind of object to serve up, DI isn't applicable there, except you can have the DI container inject the factory where you want it and manage its scope for you.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM