StructureMap injected IContainer - where does it come from?
I have an ASP.Net MVC application and I am using StructureMap within MVC to glue the whole application together. There are some model classes that have heavyweight dependencies that are not used in all public methods, s开发者_如何学编程o I pass in an IContainer to the model constructor and use that to create the heavyweight dependencies on demand.
My question is where does the IContainer come from that is injected? Is it a reference to the one held centrally by MVC (it's logical parent) or is it a brand new one created and configured solely for this class?
The container injected into a constructor that has an IContainer parameter is the same container that is creating the instance of the class with the constructor.
Jeremy Miller has expressed this behaviour as "IContainer is injected into itself by default" in his blog post on NHibernate with StructureMap.
Couldn't you go with a factory model for creating those dependencies when needed in order to reduce your coupling to the container?
You could make your model take a Func as parameter and use SM's ability to autoinject those:
public class MyModel
{
Func<IHeavyDep> _heavyFactory;
public MyModel(Func<IHeavyDep> dependency)
{
_heavyFactory = dependency;
}
public void UsesHeavy()
{
var heavy = _heavyFactory();
heavy.DoMyStuff();
}
}
精彩评论