I'm trying to use StructureMap to swap out implementations at request time based on some aspect of the request (certain combinations of parameters). Some of these dependencies are deeply nested in the object graph.
For a number of reasons, I want to do this at the start of the request pipeline - so I'd like to swap out all of the nested dependencies before resolving the top-level service and avoid injecting factories.
Currently, I've achieved this by creating a nested container for each request. Something along the lines of:
using(var nested = _container.GetNestedContainer())
{
foreach(var service in services)
{
nested.For(service.InterfaceType).Use(service.ImplementationType);
}
nested.GetInstance<IRequestHandler>().Invoke(request);
}
From what I've read, though, this seems like an abuse of nested containers, which are intended primarily for lifecycle management (I'm also concerned about potential performance implications and any other potential gotchas).
I've also attempted to use .With
on the main container when resolving the entry point...
var entryPoint = _container.With(typeof(ISomeNestedDependency),
typeof(ImplementationForThisRequest))
.Resolve<IRequestHandler>();
entryPoint.Invoke(request);
... but this seems to register the type associated with the first request in the container and then always resolve that type from that point on (presumably for the lifetime of the container itself).
What's the proper way to approach this with StructureMap 3? Is there one?