DI and Singleton Pattern in one implementation

风格不统一 提交于 2019-12-30 03:30:19

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/1917180/di-and-singleton-pattern-in-one-implementation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!