Difficulty getting the Unity dependency injection running with the Web API and OWIN

advertisements

When I try to call a controller API endpoint on my application I get this error:

   {
  "Message": "An error has occurred.",
  "ExceptionMessage": "An error occurred when trying to create a controller of type 'ProviderController'. Make sure that the controller has a parameterless public constructor.",
  "ExceptionType": "System.InvalidOperationException",
  "StackTrace": "   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()",
  "InnerException": {
    "Message": "An error has occurred.",
    "ExceptionMessage": "Type 'mynamespace.api.controllers.ProviderController' does not have a default constructor",
    "ExceptionType": "System.ArgumentException",
    "StackTrace": "   at System.Linq.Expressions.Expression.New(Type type)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"
  }
}

My configuration is as follows and I am using the Unity.WebAPI library:

Startup.cs

    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = GlobalConfiguration.Configuration;
        config.DependencyResolver = new UnityDependencyResolver(UnityConfig.GetConfiguredContainer());
        app.UseWebApi(WebApiConfig.Register());
        app.UseCors(CorsOptions.AllowAll);

        config.EnsureInitialized();

    }

UnityConfig.cs:

public static class UnityConfig
{
    #region Unity Container

    /// <summary>
    /// Load types in Unity Container
    /// </summary>
    private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
    {
        var container = new UnityContainer();
        RegisterTypes(container);
        return container;
    });

    /// <summary>
    /// Gets the configured Unity container.
    /// </summary>
    public static IUnityContainer GetConfiguredContainer()
    {
        return container.Value;
    }

    #endregion

    /// <summary>
    /// Register the types into Unity Container.
    /// </summary>
    /// <param name="container"></param>
    public static void RegisterTypes(UnityContainer container)
    {
        container.RegisterType<IProviderService, ProviderService();
    }
}

ProviderController.cs:

public class ProviderController : ApiController
{
    private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
    private readonly IProviderService providerService;      

    public ProviderController(IProviderService providerService)
    {
        providerService = providerService;
    }

    //Controller API Methods
}

ProviderService.cs:

    public ProviderService()
    {
        this.serviceClient = new ServiceClientAdapter();
    }

I have spent all morning reading through various threads and am unable to figure out where I am going wrong. If I remove Unity and instantiate a new ProviderService directly in the controller, everything works.


My problem was a small oversight. The call to UseWebApi in Startup.cs was not taking the HttpConfiguration config object as a parameter but was instead declaring it's own. This meant that WebAPI and Unity were configured with different HTTPConfiguration objects and the WebAPI was not aware of Unity as a result.