Search code examples
c#asp.net-web-api2simple-injector

Simple Injector Container Fails To Register Web API Controller From Pluggedin External Library


The issue was noticed with the call to the extension method container.RegisterWebApiControllers(GlobalConfiguration.Configuration) on the container that's supposed to register the web api controller with the container but didn't. Please note that the web api controllers are defined in a different class library project and plugged at application start up using a custom IAssembliesResolver type.

public static class SimpleInjectorWebApiInitializer
{
    public static void Initialize()
    {
        var container = new Container();

        GlobalConfiguration.Configuration.Services.Replace(typeof(IAssembliesResolver),
            new ApiAssemblyResolver());

        InitializeContainer(container);

        container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

        container.Verify();

        GlobalConfiguration.Configuration.DependencyResolver = 
            new SimpleInjectorWebApiDependencyResolver(container);
    }

I even tried to call to get the ControllerTypes manually to see what was going on using the code below but it never triggered the GetAssemblies method neither did it return any ControllerTypes.

var controllerTypes = httpConfigServicesContainer.GetHttpControllerTypeResolver()
    .GetControllerTypes(
        GlobalConfiguration.Configuration.Services.GetAssembliesResolver());

I am almost pulling out all my hair as I can't seem to see what I am doing wrong. Thanks for your help in advance.


Solution

  • The solution lay in the order in which configuration calls were made. I moved every call for configuration involving the IOC container into the Application_Start method of Global.asax file.

    Before making the call to GlobalConfiguration.Configure(WebApiConfig.Register), I had already called

    GlobalConfiguration.Configuration.Services.Replace(typeof(IAssembliesResolver), new ApiAssemblyResolver())
    

    to replace the default assemblies resolver. I finally placed the other container web api configuration settings after every other configuration call and it started working like a charm! I.e

    var apiIOCContainer = new Container();
    SimpleInjectorWebApiInitializer.InitializeContainer(apiIOCContainer);
    apiIOCContainer.RegisterWebApiControllers(GlobalConfiguration.Configuration);
    GlobalConfiguration.Configuration.DependencyResolver =
    new SimpleInjectorWebApiDependencyResolver(apiIOCContainer);