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.
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.
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