Ninject.ActivationException thrown only on first web request (WebAPI 2, OWIN 3, Ninject 3)
Asked Answered
B

3

29

I am attempting to create a "barebones" Web API project that uses OWIN middleware, Ninject Depencency Injection, and ultimately to be hosted in IIS. I have followed instructions found in an article, "Befriending ASP.NET Web.API2, OWIN and Ninject," here: http://www.alexzaitzev.pro/2014/11/webapi2-owin-and-ninject.html, except I used an empty Web Application Project, and did not tick the "Include Web API references and folders" when creating the project.

When I fire up the new API and make a page request, I get the following Ninject.ActivationException thrown:

Server Error in '/' Application.

Error activating HttpConfiguration
More than one matching bindings are available.
Matching bindings:
 1) binding from HttpConfiguration to method
 2) binding from HttpConfiguration to constant value
Activation path:
 1) Request for HttpConfiguration

Suggestions:
 1) Ensure that you have defined a binding for HttpConfiguration only once.

This exception goes away when I refresh my browser. I really don't understand what is causing this exception. From my point of view, being somewhat inexperienced with WebAPI in OWIN context and Ninject, it's hard to know where the problem lies. Is it with Ninject...? Is it in OWIN...? Is it in WebAPI...?

This is the content of my Startup.cs file:

using System.Web.Http;
using LHD.API_2;
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Ninject.Web.Common.OwinHost;
using Ninject.Web.WebApi.OwinHost;
using Owin;

[assembly: OwinStartup(typeof(Startup))]

namespace LHD.API_2
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute("API Default", "api/1/{controller}/{action}/{id}", new { id = RouteParameter.Optional });

            app.UseNinjectMiddleware(() => NinjectConfig.CreateKernel.Value);
            app.UseNinjectWebApi(config);
        }
    }
}

This is the content of my NinjectConfig.cs file:

using System;
using System.Reflection;
using Ninject;

namespace LHD.API_2
{
    public static class NinjectConfig
    {
        public static Lazy<IKernel> CreateKernel = new Lazy<IKernel>(() =>
        {
            StandardKernel kernel = new StandardKernel();
            kernel.Load(Assembly.GetExecutingAssembly());

            RegisterServices(kernel);

            return kernel;
        });

        private static void RegisterServices(KernelBase kernel)
        {
            // TODO - put in registrations here...

            //kernel.Bind<IFakeService>().To<FakeService>();
        }
    }
}

This is the content of my packages.config:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.AspNet.WebApi" version="5.0.0" targetFramework="net451" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net451" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net451" />
  <package id="Microsoft.AspNet.WebApi.Owin" version="5.2.3" targetFramework="net451" />
  <package id="Microsoft.AspNet.WebApi.WebHost" version="5.0.0" targetFramework="net451" />
  <package id="Microsoft.Owin" version="3.0.1" targetFramework="net451" />
  <package id="Microsoft.Owin.Host.SystemWeb" version="3.0.1" targetFramework="net451" />
  <package id="Newtonsoft.Json" version="6.0.4" targetFramework="net451" />
  <package id="Ninject" version="3.2.0.0" targetFramework="net451" />
  <package id="Ninject.Extensions.ContextPreservation" version="3.2.0.0" targetFramework="net451" />
  <package id="Ninject.Extensions.NamedScope" version="3.2.0.0" targetFramework="net451" />
  <package id="Ninject.Web.Common" version="3.2.0.0" targetFramework="net451" />
  <package id="Ninject.Web.Common.OwinHost" version="3.2.3.0" targetFramework="net451" />
  <package id="Ninject.Web.WebApi" version="3.2.0.0" targetFramework="net451" />
  <package id="Ninject.Web.WebApi.OwinHost" version="3.2.4.0" targetFramework="net451" />
  <package id="Owin" version="1.0" targetFramework="net451" />
</packages>

... and, for the sake of completeness, the content of my web.config is similarly unspectacular:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.5.1" />
        <httpRuntime targetFramework="4.5.1" />
    </system.web>

    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Http.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
<system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
</configuration>

Can anyone point me towards what I'm doing wrong, or more importantly, what I can change to get things working without the exception being thrown?

Bluefield answered 25/2, 2015 at 5:39 Comment(0)
S
61

What version of the Ninject.Web.WebApi library are you using? it looks like 2 weeks ago a change was made to move some things around. before this change (v3.2.3 and earlier), HttpConfiguration bindings were present in 2 different modules in Ninject.Web.WebApi.OwinHost.OwinWebApiModule and Ninject.Web.WebApi.WebApiModule. after this change (new version is 3.2.4), this binding only happens once.

Schilling answered 26/2, 2015 at 15:44 Comment(2)
Thanks @dave-thieben. Updating to the latest Ninject packages did indeed solve my issues.Bluefield
I installed the Ninject.Web.WebApi.WebHost' Nuget package version 3.2.4. This installed the dependency on Ninject.Web.WebApi` but used version 3.2.0. Upgrading to the latest (3.2.4) fixed it for meParticia
G
16

I had the same error, but for a different reason: for some reason I had installed both Ninject.Web.WebApi.WebHost and Ninject.Web.WebApi.OwinHost.

If you look in source for OwinWebApiModule.cs and WebApiWebHostModule.cs, both Ninject modules have a binding for HttpConfiguration.

I removed Ninject.Web.WebApi.WebHost and all is well.

Groove answered 9/7, 2015 at 12:18 Comment(1)
We have this issue but not sure how to solve it as we need an owin startup for self hosting and a webhost for IIS general usage, whenever we use ninject via owinhost it blows up on the first request as mentioned, but as we need both dlls in the application is there a workaround? (We did try putting our self host elsewhere but unless it was a console or web app it didnt work due to startup not being found so we just moved it back into the webapi project where the config for it was anyway.Jehad
U
6

Go to the Referances and search for Ninject.web.WebApi.WebHost and then remove this.Thats all it will start working.

Undercool answered 5/10, 2016 at 11:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.