所以我一直在使用 ASP.NET MVC 2(目前坚持使用 Visual Studio 2008),现在开始使用 Ninject 2.2 及其 MVC 集成。我从以下位置下载了 Ninject 2.2 和 Ninject.Web.Mvc:
https://github.com/downloads/ninject/ninject/Ninject-2.2.0.0-release-net-3.5.zip
https://github.com/downloads/ninject/ninject.web.mvc/Ninject.Web.Mvc2-2.2.0.0-release-net-3.5.zip
并在我的 MVC 2 项目中引用了它们。我的 Global.asax.cs 文件看起来像这样(几乎是 Ninject.Web.Mvc README 所说的):
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Ninject.Web.Mvc;
using Ninject;
namespace Mvc2 {
public class MvcApplication : NinjectHttpApplication {
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
);
}
protected override void OnApplicationStarted() {
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
protected override IKernel CreateKernel() {
var kernel = new StandardKernel();
kernel.Bind<IFoo>().To<Foo>();
return kernel;
}
}
}
还有一个看起来像这样的家庭 Controller :
using System;
using System.Web;
using System.Web.Mvc;
namespace Mvc2.Controllers {
public class HomeController : Controller {
private readonly IFoo foo;
public HomeController(IFoo foo) {
this.foo = foo;
}
public ActionResult Index() {
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
}
}
现在,每次我运行我的项目并访问“/”时,我都会看到一个黄色的死机屏幕,并显示一条消息“没有为此对象定义无参数构造函数”。似乎 Ninject 没有解决我的 Foo 服务并将其注入(inject) HomeController。我想我错过了一些非常明显的东西,但我只是没有看到它。
如何让 Ninject 将 Foo 注入(inject) HomeController,而不使用 Ninject 属性?
最佳答案
我:你能提供更多关于 IFoo 服务实现的信息吗?它是否满足了自己的所有依赖项?
我自己:嗯,不,它没有。原来我没有绑定(bind)它的依赖项。男孩,该错误消息和堆栈跟踪是否具有误导性!
所以我的错误是我没有绑定(bind) IFoo 实现的依赖项之一,因此 Ninject 默默地失败并试图继续其愉快的方式。这真的很不幸,因为一旦我偏离了一个琐碎的设置,它可能会导致一些非常奇怪的行为。我想我的下一个问题应该是如何让 Ninject 尽早失败并提供有关问题所在的良好消息?但现在我至少可以继续下去。
关于asp.net-mvc - ASP.NET MVC 2、Ninject 2.2 并且没有为此对象定义无参数构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5765286/