I am using StructureMap
as my IoC container in a WebAPI project. I want to provide different implementations of certain dependencies based on values in the request (query string or http headers).
StructureMap has the concept of Profiles for this, which is absolutely perfect, I can override dependencies like this:
For<ISomeDependency>().Use<StandardImplementation>();
Profile("AlternateProfile", pr =>
{
pr.For<ISomeDependency>().Use<AlternateImplementation>();
});
However, I can't figure out where I can use this profile in the WebAPI lifecycle. Seems like it should be in IDependencyResolver.BeginScope()
which would allow me to do this:
public IDependencyScope BeginScope()
{
var request = ??!?
if (/* Check an HTTP Header for the request or something here? */)
child = _container.GetNestedContainer("AlternateProfile");
else
child = _container.GetNestedContainer();
return new WebApiStructureMapDependencyResolver(child);
}
The DI setup in WebAPI does seem half-baked, but I hope I'm just missing something stupid.
NOTE: I am using WebAPI self-hosted so can't use the workarounds like this: https://stackoverflow.com/a/19776966