Skip to content

Ninject.ActivationException thrown on first web request; subsequent requests are OK #166

@jnpwly

Description

@jnpwly

I have been attempting to build an OWIN WebAPI project with Ninject as the IOC. I created a completely empty Web Application Project in VS2013 (and explicitly choose not to include references or folders for WebAPI), and then manually install the following packages via the Package Manager Console:

  • Install-Package Microsoft.AspNet.WebApi.Owin
  • Install-Package Microsoft.Owin.Host.SystemWeb
  • Install-Package Ninject.Web.Common.OwinHost (note: at this stage, the package installation fails, with the message Updating 'Microsoft.Owin 3.0.0' to 'Microsoft.Owin 2.0.0' failed. Unable to find versions of 'Microsoft.AspNet.WebApi.Owin, Microsoft.Owin.Host.SystemWeb' that are compatible w ith 'Microsoft.Owin 2.0.0'. This problem-ette is resolved by using the command Install-Package Ninject.Web.WebApi.OwinHost -DependencyVersion highest.)
  • Install-Package Ninject.Web.WebApi.OwinHost
    This results in a packages.config file with the following content:
<?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>

I then created the following classes:

The 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);
        }
    }
}

The 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>();
        }
    }
}

... and for completeness, this is the web.config file:

<?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>

When I fire up this web app, the first web request fails, as a Ninject.ActivationException is 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.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: Ninject.ActivationException: 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.


Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[ActivationException: 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.
]
   Ninject.KernelBase.Resolve(IRequest request) +1265
   Ninject.ResolutionExtensions.GetResolutionIterator(IResolutionRoot root, Type service, Func`2 constraint, IEnumerable`1 parameters, Boolean isOptional, Boolean isUnique) +129
   Ninject.ResolutionExtensions.Get(IResolutionRoot root, IParameter[] parameters) +128
   Ninject.Web.WebApi.NinjectWebApiHttpApplicationPlugin.Start() +77
   Ninject.Web.Common.Bootstrapper.<Initialize>b__0(INinjectHttpApplicationPlugin c) +29
   Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map(IEnumerable`1 series, Action`1 action) +194
   Ninject.Web.Common.Bootstrapper.Initialize(Func`1 createKernelCallback) +205
   Ninject.Web.Common.OwinHost.<Execute>d__1.MoveNext() +259
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<RunApp>d__5.MoveNext() +287
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<DoFinalWork>d__2.MoveNext() +272
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +22
   Microsoft.Owin.Host.SystemWeb.Infrastructure.ErrorState.Rethrow() +33
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +150
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +42
   System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +415
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

If I then hit F5 in the browser, the subsequent request succeeds; well, it does not have the exception thrown.

Because of my lack of experience with OWIN, WebAPI and Ninject, I am unable to exactly work out why this exception is occurring. However, if I make it so that the packages.config file has the following content (i.e. the specific versions of the NuGet packages are installed), then the Web App does not experience the Ninject.ActivationException on the first request:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.AspNet.WebApi" version="5.2.2" 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.2.2" targetFramework="net451" />
  <package id="Microsoft.Owin" version="3.0.0" targetFramework="net451" />
  <package id="Microsoft.Owin.Host.SystemWeb" version="3.0.0" targetFramework="net451" />
  <package id="Newtonsoft.Json" version="6.0.4" targetFramework="net451" />
  <package id="Ninject" version="3.2.2.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.3.0" targetFramework="net451" />
  <package id="Ninject.Web.Common.OwinHost" version="3.2.3.0" targetFramework="net451" />
  <package id="Ninject.Web.WebApi" version="3.2.4.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>

What is it about the particular combination of Microsoft.Owin v3.0.1 and Ninject v3.2.0.0 (which appear to be the combination that gets installed if no specific versions are specified...??) that causes this exception?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions