The static container already has a kernel associated with it! when deployed to a virtual application

2

I am trying to get ninject to work in a production environment.

My solution consists of the following projects

  • Data
  • Model
  • WebApi2
  • MVC5

Everything is getting deployed as webrole to azure.

My api is setup as a virtual application below the mvc site. My application is a multi tenant application so I want users to be able to access the api the same way as the application does e.g.

https://theirbusiness.mydomain.com/api/api-call

For my local development I am using 2 sites not a virtual application as I had to many issues trying to battle with azure to get it working locally. So my service definition has 2 sites created for local work. Locally I have no issues

My website and api both have reference to ninject, my data and model do not.

When I deploy and try to hit the api I get an error

The static container already has a kernel associated with it!

The website doesnt have any issues it just seems to be the api. I added ninject to both using nuget

The stack trace

[NotSupportedException: The static container already has a kernel associated with it!] Ninject.Web.KernelContainer.set_Kernel(IKernel value) +193 Ninject.Web.NinjectWebHttpApplicationPlugin.Start() +82 Ninject.Web.Common.Bootstrapper.b__0(INinjectHttpApplicationPlugin c) +89 Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map(IEnumerable1 series, Action1 action) +283 Ninject.Web.Common.Bootstrapper.Initialize(Func`1 createKernelCallback) +410 MyNameSpace.Application.Api.App_Start.NinjectWebCommon.Start() +362

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
 System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +417
 System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +35
 WebActivator.BaseActivationMethodAttribute.InvokeMethod() +761
 WebActivator.ActivationManager.RunActivationMethods() +1177
 WebActivator.ActivationManager.RunPreStartMethods() +75
 WebActivator.ActivationManager.Run() +97

[InvalidOperationException: The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +888
System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +137
System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +160
System.Web.Compilation.BuildManager.ExecutePreAppStart() +142
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +838

[HttpException (0x80004005): The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +452
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +99
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +1017

My NinjectWebCommon.cs

using System;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
using MyNameSpace.Application.Api.App_Start;
using MyNameSpace.Application.Api.Interface;
using MyNameSpace.Application.Api.Repository;

[assembly: WebActivator.PreApplicationStartMethod(typeof(NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(NinjectWebCommon), "Stop")]


namespace MyNameSpace.Application.Api.App_Start
{
public static class NinjectWebCommon
{
    private static readonly Bootstrapper bootstrapper = new Bootstrapper();

    /// <summary>
    /// Starts the application
    /// </summary>
    public static void Start()
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(CreateKernel);
    }

    /// <summary>
    /// Stops the application.
    /// </summary>
    public static void Stop()
    {
        bootstrapper.ShutDown();
    }

    /// <summary>
    /// Creates the kernel that will manage your application.
    /// </summary>
    /// <returns>The created kernel.</returns>
    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

        RegisterServices(kernel);
        GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
        return kernel;
    }

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
                  kernel.Bind<IBusinessRepository>().ToConstant(new BusinessRepository());
                  kernel.Bind<IEmployeeRepository>().ToConstant(new EmployeeRepository());

    }
}

}

My Dependency scope

public class NinjectDependencyScope : IDependencyScope
{
private IResolutionRoot resolver;

internal NinjectDependencyScope(IResolutionRoot resolver)
{
    Contract.Assert(resolver != null);

    this.resolver = resolver;
}

public void Dispose()
{
    IDisposable disposable = resolver as IDisposable;
    if (disposable != null)
        disposable.Dispose();

    resolver = null;
}

public object GetService(Type serviceType)
{
    if (resolver == null)
        throw new ObjectDisposedException("this", "This scope has already been disposed");

    return resolver.TryGet(serviceType);
}

public IEnumerable<object> GetServices(Type serviceType)
{
    if (resolver == null)
        throw new ObjectDisposedException("this", "This scope has already been disposed");

    return resolver.GetAll(serviceType);
}
}

public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
{
private IKernel kernel;

public NinjectDependencyResolver(IKernel kernel)
    : base(kernel)
{
    this.kernel = kernel;
}

public IDependencyScope BeginScope()
{
    return new NinjectDependencyScope(kernel.BeginBlock());
}
}

If I debug locally. Setting the api as my startup project I can run the application without any problems as soon as I deploy it, it fails. I remote logged into the azure webrole and deleted the mvc site keeping just the api site as the root site. This did not help the issue.

Does something look wrong in my above setup?

asp.net-mvc
azure
dependency-injection
asp.net-web-api
ninject
asked on Stack Overflow Oct 28, 2013 by Diver Dan

2 Answers

0

I believe your problem is the same as mine. The problem is that you have duplicate Ninject.dll or whatever dll from Ninject in your production environment. You have to clean all your existing files before you deploy again. See my solution here:

The static container already has a kernel associated with it

answered on Stack Overflow Dec 27, 2014 by martial • edited May 23, 2017 by Community
0

This happened to me, and I just commented on this line: bootstrapper.Initialize(CreateKernel) and the problem it's over.

answered on Stack Overflow May 3, 2021 by Maikiely Malini • edited May 5, 2021 by Minal Chauhan

User contributions licensed under CC BY-SA 3.0