asp.net-web-apistructuremapasp.net-web-api2

How to configure Web API 2 and Structure Map


I've trawled through multiple blogs etc trying to find out how to configure StructureMap with Web API 2 and none of the implementations worked for me. The confusion seems to be around the different IDependency Resolver that MVC uses and the one that Web API uses.

Firstly, which is the correct Nuget package and secondly, how do you configure it with a pure Web API 2 project?

Thanks

This is what I have so far and it seems to be working. Is this correct?

public class StructureMapControllerActivator : IHttpControllerActivator
{
    private readonly IContainer _container;

    public StructureMapControllerActivator(IContainer container)
    {
        if (container == null) throw new ArgumentNullException("container");
        _container = container;
    }

    public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
    {
        try
        {
            var scopedContainer = _container.GetNestedContainer();
            scopedContainer.Inject(typeof(HttpRequestMessage), request);
            request.RegisterForDispose(scopedContainer);
            return (IHttpController)scopedContainer.GetInstance(controllerType);
        }
        catch (Exception e)
        {
            // TODO : Logging
            throw e;
        }
    }
}

Solution

  • There are few links, were I've tried to explain how we can use (easily) StructureMap and Web API together:

    We have to implement the IHttpControllerActivator, which could profit from already configured StructureMap ObjectFactory:

    public class ServiceActivator : IHttpControllerActivator
    {
        public ServiceActivator(HttpConfiguration configuration) {}    
    
        public IHttpController Create(HttpRequestMessage request
            , HttpControllerDescriptor controllerDescriptor, Type controllerType)
        {
            var controller = ObjectFactory.GetInstance(controllerType) as IHttpController;
            return controller;
        }
    }
    

    And then, we have to just register our implementation (global.asax):

    protected void Application_Start()
    {
        ...
        HttpConfiguration config = GlobalConfiguration.Configuration;
        config.Services
              .Replace(typeof(IHttpControllerActivator), new ServiceActivator(config));
        ...