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

人盡茶涼 提交于 2019-12-06 11:43:52
Josh Kodroff

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.

NightOwl888

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.

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