因此,我花了一些时间在ASP.NET MVC 2(目前仍停留在使用Visual 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自述内容大致相同):
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;
}
}
}和一个看起来像这样的家庭控制器
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();
}
}
}现在,每当我运行我的项目并访问'/‘时,我都会看到一个黄色的死亡屏幕,上面写着“没有为这个对象定义无参数构造函数”。尼尼姆似乎没有解决我的Foo服务,并将其注入HomeController。我想我错过了一些很明显的东西,但我就是没看到。
如何在不使用HomeController属性的情况下将Foo注入到中?
发布于 2011-04-24 19:04:05
我:你能提供一些关于IFoo服务实现的更多信息吗?它是否满足了它自己的所有依赖?
我自己:嗯,不,没有。原来我没有绑定它的依赖关系。孩子,那是错误信息和堆栈跟踪误导!
因此,我的错误是,我没有绑定IFoo实现的依赖项之一,因此Ninject默默地失败了,并试图继续它的快乐之路。这是非常不幸的,因为一旦我偏离了一个琐碎的设置,它可能会导致一些非常奇怪的行为。我想我的下一个问题应该是,我怎样才能尽早让尼尼莫失败,并提供关于哪里出了问题的好消息?但现在我至少还能继续干下去。
https://stackoverflow.com/questions/5765286
复制相似问题