Search code examples
c#asp.net-web-apikatana

Unity Dependency Resolver not working with Katana and WebAPI?


I tried Unity 3 for a WebAPI hosted in Katana.

I get a exception that system.web.http cant be loaded on the Startup.

Anyone made this work?

HttpConfiguration apiConfig = new HttpConfiguration();

apiConfig.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);
apiConfig.Formatters.Remove(apiConfig.Formatters.XmlFormatter);
apiConfig.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
apiConfig.DependencyResolver = new UnityDependencyResolver(_container);

app.UseWebApi(apiConfig);

Solution

  • If you are using Unity.WebAPI package, it depends on System.Web.Http v4.0. In order to use it in Web API v2, you need to add assembly binding redirect to web.config:

      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
          </dependentAssembly>
        </assemblyBinding>
      </runtime>