Ninject + MVC3 = InvalidOperationException:序列不包含任何元素 [英] Ninject + MVC3 = InvalidOperationException: Sequence contains no elements
问题描述
我创建了一个新的 MVC3 项目,按 F5,看到示例页面.
I created a new MVC3 project, hit F5, saw the sample page.
然后我使用 NuGet 来获取 Ninject.MVC 扩展.我根据 Ninject 文档修改了我的 global.asax,如何设置 MVC3 应用程序:
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 - 序列不包含任何元素.
InvalidOperationException - Sequence contains no elements.
在 System.Linq.Enumerable.Single(...)
at System.Linq.Enumerable.Single(...)
在 Ninject.Web.Mvc.Bootstrapper.Initialize(...)第 67 行.
at Ninject.Web.Mvc.Bootstrapper.Initialize(...) line 67.
果然,该文件的第 67 行 调用 .Single(),从而抛出异常.
And sure enough, line 67 of that file calls .Single(), thus throwing the exception.
我做错了什么?
推荐答案
您可能会注意到,在安装 ninject.mvc3
NuGet 后,在您的内部创建了一个 App_Start
子文件夹包含 NinjectMVC3.cs
文件的项目.删除此文件夹并重试.所以这是我遵循的步骤:
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:
- 使用默认模板创建一个新的 ASP.NET MVC 3 项目
- 打开包管理器控制台窗口(查看 -> 其他窗口 -> 包管理器控制台)
- 在命令行输入
install-package ninject.mvc3
- 将
Global.asax
中的默认代码替换为您问题中的代码 - 删除在安装包期间创建的
AppStart
子文件夹 - 运行应用程序
- 享受在 Google Chrome 网络浏览器中打开的
/Home/Index
默认页面的美妙之处:-)
- Create a new ASP.NET MVC 3 project using the default template
- Bring up the Package Manager Console window (View -> Other Windows -> Package Manager Console)
- Type
install-package ninject.mvc3
on the command line - Replace the default code in
Global.asax
with the code in your question - Delete the
AppStart
subfolder created during the installation of the package - Run the application
- Enjoy the beauty of the
/Home/Index
default page opened in your Google Chrome web browser :-)
这篇关于Ninject + MVC3 = InvalidOperationException:序列不包含任何元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!