How do I use Structuremap 3 with objects that aren't friendly to constructor injection?

南楼画角 提交于 2019-12-07 22:06:49

问题


I'm moving from StructureMap 2.x to 3.x. One major change is that using ObjectFactory results in the following warning:

'StructureMap.ObjectFactory' is obsolete: 'ObjectFactory will be removed in a future 4.0 release of StructureMap. Favor the usage of the Container class for future work'

So in most cases, the resolution is fairly easy: pass through IContainer as a constructor. Unfortunately this is not feasible for ASMX web serivces or attributes, both of which require a default constructor. That means I'm probably stuck with the Service Locator Pattern, property injection, or writing my own ObjectFactory implementation.

What's the preferred way to deal with this unfortunate problem?

Edit: It's worth mentioning that my container does an Assembly scan.


回答1:


Per Jeremy Miller, himself:

Assembly scanning isn’t cheap and you (almost?) always wanna cache the results. So, yeah, in that case you’re going to have to write your own ObjectFactory. Someday all that bad old MS tech will go away.

So in this case, this implementation is what should be done.




回答2:


The cleanest way I have seen to deal with this is to use .NET routing to take control of the entry point, then make a custom PageHandlerFactory implementation that takes the DI container as a dependency.

The custom page handler factory will then property inject the page/service after it is instantiated but before any of its events are called.

This is almost exactly the same way that IControllerFactory works with DI in MVC. In MVC, the container is injected into a custom IControllerFactory implementation at application startup, which effectively makes it a part of the application's composition root. In the case of ASP.NET, the IRouteHandler would effectively be part of the composition root.

I was unable to find a link to the source where I originally saw that implementation. But this one is pretty close. The primary difference is that one tries to use constructor injection, but the downside is that it requires full trust to do. I believe if you stick with property injection, you can do it with partial trust.



来源:https://stackoverflow.com/questions/29042211/how-do-i-use-structuremap-3-with-objects-that-arent-friendly-to-constructor-inj

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