2011-04-23 40 views
5

所以我一直花費一些時間用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屬性?

+0

快樂復活節男人:) – systempuntoout 2011-04-24 12:03:22

+0

復活節快樂給你也@系統! – 2011-04-24 17:02:20

+0

七月四日之後的快樂日子。感謝發佈這個和你的答案! – anon 2011-07-06 02:04:59

回答

4

:你能提供一些關於IFoo服務實現的更多信息嗎?它是否滿足所有自己的依賴關係?

我自己:嗯,不,它沒有。原來我沒有綁定它的依賴關係。男孩,是錯誤消息和堆棧跟蹤誤導!


所以我的錯誤是,我沒有綁定的IFoo實現的一個依賴等Ninject默默失敗,並試圖繼續其快樂的方式。這是非常不幸的,因爲一旦我偏離了簡單的設置,它可能會導致一些非常奇怪的行爲。我想我的下一個問題應該是如何讓Ninject儘早失敗,並提供有關錯誤的良好信息?但現在我至少可以繼續。

相關問題