注入 + MVC3 = InvalidOperationException: 序列不包含任何元素

我创建了一个新的 MVC3项目,点击 F5,看到了样本页面。

然后我使用 NuGet 获得了 Ninject.MVC 扩展:

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

现在,当我运行这个应用程序时,我会看到黄色的死亡屏幕,除了以下例外:

序列不包含任何元素。

在系统。林克。可枚举。单(...)

在 Ninject。网络。 Mvc。引导程序。初始化(...) 67号线。

果然,第67行调用.Single () ,因此抛出异常。

我做错了什么?

21348 次浏览

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 :-)

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.

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!

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<

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.

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.

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