35
votes

I've created an empty Asp.Net MVC3 project, and used nuget install-package Ninject.MVC3

Without doing anything else (no services registered and not even a controller created) I run the application.

The Project breaks on line 22 in NinjectMVC3.cs with the following exception:

[InvalidOperationException: Already Initialized!] Ninject.Web.Mvc.Bootstrapper.Initialize(Func`1 createKernelCallback) in c:\Projects\Ninject\Maintenance2.2\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\Bootstrapper.cs> :58 Mvc.App_Start.NinjectMVC3.Start() in c:\Projects\Events\Events\App_Start\NinjectMVC3.cs:22

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner) +0
System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner) +72
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) +335
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +28
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +19
WebActivator.BaseActivationMethodAttribute.InvokeMethod() +199 WebActivator.ActivationManager.RunActivationMethods() +330 WebActivator.ActivationManager.RunPreStartMethods() +27 WebActivator.ActivationManager.Run() +39

The line in NinjectMVC3.cs is:

public static void Start() 
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestModule));
            DynamicModuleUtility.RegisterModule(typeof(HttpApplicationInitializationModule));
            bootstrapper.Initialize(CreateKernel); // <- this one right here...
        }

What is going on with this? I've used Ninject for MVC3 in other projects without problems at all. I do notice that the second line in the Start() method is not included in older (weeks) packages of Ninject.MVC3, so maybe something else has been broken in a recent update also?

Please help!

Edit to address answer from Remo

This is from my global.asax.cs

 public class MvcApplication : System.Web.HttpApplication
 {

The global.asax is 100% standard aswell. No adjustments done.

EDIT - Problem is gone...

I honestly have no idea what caused this, but after a few restarts of Visual Studio, and a full reboot, the project is working as it should. Neither can I recreate the problem in new projects.

Sorry for wasting your time :)

15
not quite sure what to do with this question, since there probably is no correct answer.. Do I flag it, close it or something?Yngve B-Nilsen
You can either select the answer that helped the most, or answer it yourself with details about what you did (essentially, your edit). Seems odd, but that's the way this is normally handled.user1228

15 Answers

34
votes

Take a look at Setting up a MVC3-application

In short:

You probably have een App_Start folder in your project with a NinjectMVC3.cs file.

When using the NuGet package in combination with modifying the Global.asax (for which there is no reason) you have to remove the App_Start folder and remove the references to WebActivator and Microsoft.Web.Infrastructure

16
votes

This situation came up for me when i changed the namespaces of my project, then switched it back again.

even when i cleaned the solution and did an iisreset it came back with 'already initialized'.

the problem arose from the dlls that had been created in the bin directory when i changed the namespace and built the project - after changing the namespaces back and cleaning the solution the dlls from the alternative namespace were still there, and hence were being loaded when the web application started up, causing the 'already initialized' error.

deleting the dlls fixed the issue.

12
votes

Most likely you are deriving from NinjectHttpApplication and using AppStart at the same time. These two ways shouldn't be mixed up.

Read the documentation https://github.com/ninject/ninject.web.mvc/wiki/Setting-up-an-MVC3-application

5
votes

I recently ran into the same problem. In my case, I have multiple projects in my solution... and more that one of those projects contains NuGet package references to Ninject.MVC3.

When I updated all of my Ninject package versions, App_Start folders were created on all of the projects that have NuGet references. So, I had to go and delete the App_Start folders from the class library projects; just leaving the App_Start folder on the main MVC application.

3
votes

I'm not sure what it was that was causing your application to bomb, but I'm glad doing VS restarts solved it. I had the same error happening but was unable to correct it no matter how many clean/rebuilds I did or how many times I restarted VS.

What ended up working for me was to remove the Ninject MVC NuGet Package completely and just add the Ninject and Ninject dll's the old fashioned way. I think there may be something wrong with their NuGet package.

I hope this helps someone else, I wasted a few hours on it when all I needed was to dump the NuGet Package.

3
votes

Problem is gone...

I honestly have no idea what caused this, but after a few restarts of Visual Studio, and a full reboot, the project is working as it should. Neither can I recreate the problem in new projects.

Sorry for wasting your time :)

UPDATE

Since posting this answer a few good answers has appeared. I'm updating this answer to collect the different approaches in one answer. Hope that's ok for you guys:

DevilDog74 answered

finally i went to gitub and cloned a new repo, downloaded the latest Ninject.Web.Common and latest Ninject2 release builds and did a local release build. then I ditched the nuget packages and made assembly references to the newly compiled > assemblies "Ninject", "Ninject.Web.Common" and "Ninject.Web.Mvc" and my project started > working and controllers were being created with their dependencies being resolved.

Jeff Circeo answered

I resolved the issue by downloading from https://github.com/ninject/ninject.web.mvc instead of using the nuget package. I didn't have to do anything after I added the references.

Marcus King answered

What ended up working for me was to remove the Ninject MVC NuGet Package completely and just add the Ninject and Ninject dll's the old fashioned way. I think there may be something wrong with their NuGet package.

2
votes

read the docs!

https://github.com/ninject/ninject.web.mvc/wiki/Setting-up-an-MVC3-application

What's the difference between these approches?

Both approaches exactly do the same. They hook Ninject into MVC applications. The only difference is that they use a different approch to do this. The reason for using different approchaches is that the NuGet package can provide out of the box integration by adding one file. Otherwise it would require complicated modifications of the global.asax

NOTE: If you decide to go with the first approach if using the NuGet package (for which there is no reason) you have to delete the App_Start folder and remove the references to WebActivator and Microsoft.Web.Infrastructure.

2
votes

I had the same problem when I upgraded the Ninject.Web.MVC3 package to version 2.2.2.0. I noticed that this update added the following line to my .csproj file (VCS FTW!):

<Compile Include="App_Start\NinjectMVC3.cs" />

Changing the Build action from Compile to Content for that file solved my problem. App_Start is as evil as App_Code after all...

2
votes

I solved this issue by manually removing some dlls in the /bin folder, which wasn't being removed when running the Cleanup command from Visual studio.

1
votes

I had the same issue with some slight differences I was inheriting from NinjectHttpApplication and overriding OnApplicationStarted. I resolved the issue by downloading from https://github.com/ninject/ninject.web.mvc instead of using the nuget package.

I didn't have to do anything after I added the references.

1
votes

i spent about 4 hours messing around with the nuget packages, to no avail.

finally i went to gitub and cloned a new repo, downloaded the latest Ninject.Web.Common and latest Ninject2 release builds and did a local release build.

then I ditched the nuget packages and made assembly references to the newly compiled assemblies "Ninject", "Ninject.Web.Common" and "Ninject.Web.Mvc" and my project started working and controllers were being created with their dependencies being resolved.

this is what my code looks like, but I think there may also be an issue in the nuget packages...

public class MvcApplication : NinjectHttpApplication
{
    protected override void OnApplicationStarted()
    {
        base.OnApplicationStarted();

        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

    protected override Ninject.IKernel CreateKernel()
    {
        // declaratively add the Ninject Modules that we have built to manage our dependencies...
        var modules = new INinjectModule[]{
            new RepoModule()
        };

        return new StandardKernel(modules);
    }

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

    }
}
1
votes

make sure only one assembly have the "NinjectMVC3" class ,if a.dll,b.dll all have the NinjectMVC3 class in then bin directory ,There will be such a mistake!

1
votes

I just had this same issue and I realized that it was because NuGet added NinjectMVC3.cs files to both my web app and my DAL library. Didn't realize that had occurred, but once I deleted the file from the DAL library it was fine.

0
votes

When you use nuGet there is a folder App_start being created, take a look into it.

0
votes

I'll add this as an answer only because I've not seen anyone mention it yet and it is worth checking before going off and cloning repos and whatnot.

I experienced this problem out of the blue on a solution which contains maybe 15 projects, three of which are websites. I had been working on one of the sites when I started getting this problem without me having changed anything that would obviously cause the problem: I had not just added Ninject anywhere (it was already installed and working just fine), the global asax files were not deriving from the Ninject classes and nothing was amiss in any App_Start folder.

After quite a bit of messing about with NuGet and the like to no avail (brought on by messages about unresolved references - seemed like Ninject was not being referenced properly but it was), i went through all the files I had changed paying particular attention to project and config files, and discovered that somehow Visual Studio had added one of the other websites as a project reference to the one I was trying to run. As a result the Ninject config was being run twice and causing the problem, so the root cause was the same but the method of screw-up was different.

There was no reason for that project reference, it was not there before as it wasn't a valid dependency, I did not add it manually and I still have no idea how it happened but removing it immediately fixed the problem.