Ninject + MVC3 = InvalidOperationException: Sequence contains no elements
Asked Answered
H

7

90

I created a new MVC3 project, hit F5, saw the sample page.

Then I used NuGet to get the Ninject.MVC extension. I modified my global.asax according to the Ninject documentation, How To Setup an MVC3 Application:

public class MvcApplication : NinjectHttpApplication
{
   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 });
   }

   protected override IKernel CreateKernel()
   {
       var kernel = new StandardKernel();
       kernel.Load(Assembly.GetExecutingAssembly());
       return kernel;
   }

   protected override void OnApplicationStarted()
   {
       base.OnApplicationStarted();

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

Now when I run the app, I get the yellow screen of death with the following exception:

InvalidOperationException - Sequence contains no elements.

at System.Linq.Enumerable.Single(...)

at Ninject.Web.Mvc.Bootstrapper.Initialize(...) line 67.

And sure enough, line 67 of that file calls .Single(), thus throwing the exception.

What am I doing wrong?

Hensel answered 1/3, 2011 at 22:3 Comment(0)
D
101

You might notice that after installing the ninject.mvc3 NuGet there is an App_Start subfolder created inside your project containing an NinjectMVC3.cs file. Delete this folder and try again. So here are the steps I followed:

  1. Create a new ASP.NET MVC 3 project using the default template
  2. Bring up the Package Manager Console window (View -> Other Windows -> Package Manager Console)
  3. Type install-package ninject.mvc3 on the command line
  4. Replace the default code in Global.asax with the code in your question
  5. Delete the AppStart subfolder created during the installation of the package
  6. Run the application
  7. Enjoy the beauty of the /Home/Index default page opened in your Google Chrome web browser :-)
Drippy answered 1/3, 2011 at 22:18 Comment(8)
That worked. I don't know why. I don't like fixing bugs without understanding it...but thanks, this unblocks me.Hensel
It is not a bug. The NuGet package is only uses another way to setup the kernel so that it does not have to change the global.asax. Your application used both ways simultaniously which put the extension in an invalid state as it is started two times.Riley
What's the correct way to solve this without deleting the App_Start folder?Kilt
@Kyralessa, by leaving Global.asax as is (not deriving from NinjectHttpApplication) and configuring the kernel in the ~/App_Start/NinjectMVC3.cs file (RegisterServices method).Drippy
Great answer and subsequent commentary - really helpful Darin.Pavo
After removing NinjectWebCommon from app_start I got errors on the validation. No idea why though. Validation type names in unobtrusive client validation rules must be unique. The following validation type was seen more than once: requiredTercet
after hours of searching, this answer solved my problem.thanksLangtry
This same answer also applies to using Ninject.MVC3 inside an MVC4 project. The App_Start folder will already exist, just remove the extra class added by the NuGet installer and error is fixed.Worley
F
120

I have to add to this in the hopes that someone else will resolve the issue more quickly and not want to pull out every strand of hair on their head like I almost did.

I needed to rename everything in my project to match new business terms. I changed namespaces everywhere and I even changed the Assembly Name (right-click project > properties > application tab) so that the generated assembly matches the new naming convention. The assembly rename is what made Ninject very angry!

By renaming the assembly that gets generated a new file with the new name was being created when we compiled. However, the old file with the old name was still in the bin directory! If you have Ninject activating via the added class in App_Start then this activation class will get invoked in BOTH assemblies (old one AND new renamed one). Don't ask me how or why, but it does and it gives you this "already initialized" error.

Not even cleaning solution works because Visual Studio will only remove the binaries that it is generating, which would be the new renamed ones. It leaves the old ones alone just sitting there.

Go delete your bin folder before you try doing anything else! I hope this saves someone else from wasting valuable working hours!

Foliation answered 1/3, 2012 at 7:29 Comment(12)
Well, I've wasted like 40 minutes before I've stumbled upon your answer. Thanks Alex!Speedwell
Couldn't agree more with @GunnerL3510 commentSabadilla
I didn't have to remove all the bin folder, but just the old assembly (dll + pdb file), plus all the obj folder like you mentioned and problem solved. Thanks!Minuend
Accepted answer did not do it for me but this one did. Thanks Alex.Gardenia
This happened to me without even renaming anything. I think the randomly named dll files were causing it... but cleaning out the bin directory on the server fixed it. Thanks!Medwin
I've wasted 2 hours before found this brilliant and simple answer. Thanks a lot man.Sommelier
One would think that "clean solution" would just nuke the bin and obj folders. At least that's why I thought. I'm glad I was able to help.Foliation
Thank you so much! I burned an hour on this issue, and would have burned many more without your response. This should be the correct answer to the appropriate question.Bigler
Brilliant! Thanks Alex. I wasted so much time trying to get to the bottom of this, your solution worked perfectly.Diatribe
This was fantastic. Thank you so much. I did exactly this, a full namespace renaming and didn't even attribute my issues to the fact that assembly was still built in the bin. Thank you very much!Withdrawal
Thanks! I'm using Azure to host my site and I had to FTP in and delete the bin folder on the server to get this issue to go away.Gerrilee
I faced this problem when publishing to a repurposed website (not my call) The problem for me was i was publishing to an existing website without deleting all files previously (my bad) and there were old dll's in there.. removing the dll's fixed this issue. SO THANKFUL!Recor
D
101

You might notice that after installing the ninject.mvc3 NuGet there is an App_Start subfolder created inside your project containing an NinjectMVC3.cs file. Delete this folder and try again. So here are the steps I followed:

  1. Create a new ASP.NET MVC 3 project using the default template
  2. Bring up the Package Manager Console window (View -> Other Windows -> Package Manager Console)
  3. Type install-package ninject.mvc3 on the command line
  4. Replace the default code in Global.asax with the code in your question
  5. Delete the AppStart subfolder created during the installation of the package
  6. Run the application
  7. Enjoy the beauty of the /Home/Index default page opened in your Google Chrome web browser :-)
Drippy answered 1/3, 2011 at 22:18 Comment(8)
That worked. I don't know why. I don't like fixing bugs without understanding it...but thanks, this unblocks me.Hensel
It is not a bug. The NuGet package is only uses another way to setup the kernel so that it does not have to change the global.asax. Your application used both ways simultaniously which put the extension in an invalid state as it is started two times.Riley
What's the correct way to solve this without deleting the App_Start folder?Kilt
@Kyralessa, by leaving Global.asax as is (not deriving from NinjectHttpApplication) and configuring the kernel in the ~/App_Start/NinjectMVC3.cs file (RegisterServices method).Drippy
Great answer and subsequent commentary - really helpful Darin.Pavo
After removing NinjectWebCommon from app_start I got errors on the validation. No idea why though. Validation type names in unobtrusive client validation rules must be unique. The following validation type was seen more than once: requiredTercet
after hours of searching, this answer solved my problem.thanksLangtry
This same answer also applies to using Ninject.MVC3 inside an MVC4 project. The App_Start folder will already exist, just remove the extra class added by the NuGet installer and error is fixed.Worley
R
24

I have updated the documentation Wiki linked in your question to show both ways to setup a MVC3 application. I suggest to use the second option which is the prefered way for theNuGetpackage.

Instead of deriving from NinjectHttpApplication it is using the NinjectMVC.cs in the AppStart folder which is created during installation of the package. This is also the location where you create the kernel and where you load your modules or where you define the bindings.

Riley answered 1/3, 2011 at 23:43 Comment(1)
Very helpful, Remo. Since I already marked an answer, I'll just upvote yours and maybe upvote a few others of yours. Thank you for going above and beyond in answering and updating the Wiki.Hensel
K
4

As Alex Ford said:

I have to add to this in the hopes that someone else will resolve the issue more quickly and not want to pull out every strand of hair on their head like I almost did.

I had a special version of that problem which could get solved as follows:

Exception Details: System.InvalidOperationException: Sequence contains no elements

This error is caused by the fact that there are 2 projects with App_Start/NinjectWebCommon.cs

Removing the file eliminates the error.

Note: if you are nu-getting Ninject.Web.Common because you need to reference Ninject.Web.Common assembly for one of your class library project, you can safely remove the “App_Start” folder and “NinjectWebCommon.cs”. It is meant for web/web api projects.

>click here to view the original blog entry<

Kennykeno answered 23/4, 2014 at 5:45 Comment(2)
After changing the Namespace of my projects I ran today again into the same problem. All the solutions here did not help. Cleaning & rebuilding did not help. But what helped was deleting the bin and obj folders of my project. Seems like there still stuck some pieces of the old namespace part in it that did not get deleted with a cleaning.Kennykeno
Hi Da_Wolf, Thats it. Thank you. You solved my problemAdmiralty
E
2

My solution was that I had set the App_Start folder property, Namespace Provider to True.

I had changed this to False so that Resharper wouldn't highlight the namespace NOT matching the folder structure.

Errantry answered 22/5, 2014 at 11:25 Comment(1)
This was it for me, driving me mad.Radie
P
2

Wanted to add one more cause ...

We installed the Ninject.MVC3 package to multiple projects - only one of which was an actual MVC applicaiton. However, we forgot to remove the App_Start folder.

Removing the App_Start folder from the referenced project resolved the issue.

Pelmas answered 25/11, 2014 at 21:35 Comment(1)
Yeah! This was it! I had mistakenly added a second Ninjectwebcommon.cs file on another porject! This was it (Using MVC 5)Vacuva
E
1

To tack on to @Chev's answer... this was my ultimate issue as well. If you're deploying to an Azure Website (now named AppSite), you want to click on this box in the publish to remove old files

publish to azure screenshot

Engrave answered 7/12, 2015 at 16:16 Comment(1)
This is the exact same picture I was about to post! I wish I had scrolled down to this answer, but the above answers lead me to this idea. +1Semibreve

© 2022 - 2024 — McMap. All rights reserved.