所以我一直花費一些時間用ASP.NET MVC 2(目前停留在使用Visual Studio 2008),現在已經開始使用Ninject 2.2和它的MVC整合。我從以下位置下載Ninject 2.2和Ninject.Web.Mvc:ASP.NET MVC 2,Ninject 2.2並且沒有爲這個對象定義的無參數構造函數
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();
}
}
}
現在每次我運行我的項目並訪問'/'我得到一個消息,說「沒有爲此對象定義的無參數構造函數」的黃色屏幕死亡。看來Ninject並沒有解決我的Foo服務並將其注入到HomeController中。我想我錯過了一些非常明顯的東西,但我只是沒有看到它。
如何讓Ninject將Foo注入HomeController並且不使用Ninject屬性?
快樂復活節男人:) – systempuntoout 2011-04-24 12:03:22
復活節快樂給你也@系統! – 2011-04-24 17:02:20
七月四日之後的快樂日子。感謝發佈這個和你的答案! – anon 2011-07-06 02:04:59