I'm using StructureMap 3.1.1 in a .NET MVC 5 app and am struggling to get exactly one MyDataContext (which is a wrapper to abstract away MyDbContext) created for a given HttpRequest. My container has the following mapping:
ObjectFactory.Initialize(x =>
{
x.For<DbContext>().LifecycleIs(new UniquePerRequestLifecycle()).Use<MyDbContext>();
x.For<IDataContext>().LifecycleIs(new UniquePerRequestLifecycle()).Use<MyDataContext>();
}
As I understand it, .LifecycleIs(new UniquePerRequestLifecycle()) should cause StructureMap to new up a MyDataContext and MyDbContext only once per HttpRequest. Subsequent injections of these interfaces would ideally use this same instance. In reality I'm seeing the MyDataContext constructure called 13 times when I hit a particular controller. This appears to be the number of times that MyDataContext shows up as a dependency in all of the other nested dependencies further downstream.
My controller's constructor looks something like this:
internal IGamingGroupViewModelBuilder gamingGroupViewModelBuilder;
internal IGamingGroupAccessGranter gamingGroupAccessGranter;
internal IGamingGroupCreator gamingGroupCreator;
internal IGamingGroupRetriever gamingGroupRetriever;
public GamingGroupController(
IGamingGroupViewModelBuilder gamingGroupViewModelBuilder,
IGamingGroupAccessGranter gamingGroupAccessGranter,
IGamingGroupCreator gamingGroupCreator,
IGamingGroupRetriever gamingGroupRetriever)
{
this.gamingGroupViewModelBuilder = gamingGroupViewModelBuilder;
this.gamingGroupAccessGranter = gamingGroupAccessGranter;
this.gamingGroupCreator = gamingGroupCreator;
this.gamingGroupRetriever = gamingGroupRetriever;
}
The implementations of these interfaces have constructors that take an IDataContext or another interface that in turn takes an IDataContext in the constructor of its implementation.
What am I don't wrong? How can I get StructureMap to provide the same implementation for all of these constructors? Thanks in advance and let me know if you need any additional clarification. I would love to help you help me!