0

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

Community
  • 1
  • 1
Simon
  • 5,373
  • 1
  • 34
  • 46
  • See [this answer](http://stackoverflow.com/questions/1943576/is-there-a-pattern-for-initializing-objects-created-via-a-di-container/1945023#1945023). Also, have a look at the [strategy pattern](http://stackoverflow.com/questions/31950362/factory-method-with-di-and-ioc#31971691) for an alternate way of achieving the same thing using the strategy pattern combined with abstract factories with varying dependency lists. – NightOwl888 Dec 22 '15 at 22:19
  • Thanks @NightOwl888 - I was hoping to avoid injecting a factory into the controller. Seems pretty silly that that is needed. I did find a way to do it by re-implementing a few WebAPI classes but that's not great either. – Simon Dec 27 '15 at 16:47
  • 1
    Funny, to me it seems pretty silly to try to use a DI container to resolve runtime references because DI containers are meant for [composing object graphs](http://blog.ploeh.dk/2011/07/28/CompositionRoot/). An alternative to my previous suggestions could be to [inject a function into the factory](http://stackoverflow.com/questions/31950362/factory-method-with-di-and-ioc#31956803) so you actually use the container to resolve the references. – NightOwl888 Dec 28 '15 at 01:22
  • @NightOwl888 Fair enough, I regret using the word "silly". Using a factory function might be the easiest approach in my scenario. Appreciate your input. – Simon Dec 29 '15 at 11:22

0 Answers0