At present we use StructureMap v2.6 for our dependency injection and our setup is like this:
In the Application_Start we have:
DependencyResolver.SetResolver(new StructureMapDependencyResolver(IoC.Initialize()));
And the Initialize method is implemented like this:
public static IContainer Initialize() {
ObjectFactory.Initialize(x => {
x.Scan(scan => { scan.TheCallingAssembly(); scan.WithDefaultConventions(); });
x.For<IFoo>().Use(() => new Foo());
});
return ObjectFactory.Container;
}
}
Throughout our code we have several places that use ObjectFactory.GetInstance<IFoo>()
rather than using constructor injection. With v3 of StructureMap this has been marked as obsolete, so my question is how do we achieve the same thing with the latest version.
If constructor injection is out of the question then you're left with limited options I'm afraid.
The general consensus, and suggested by StructureMaps creator in a similar question, is to roll your own ObjectFactory. Here is a simple implementation of an ObjectFactory that you can use that's referenced in the previous link.
If you're taking advantage of StructureMap's HttpContext bound nested container and the class referencing StructureMap's object factory is located in the UI layer then another option available to you is to grab your nested container directly from HttpContext.Items
. This is a little dirty but it can be done.