2011-12-23 237 views
1

我開始使用MVC4的新項目,並希望使用依賴注入。我過去沒有使用它,但現在看來是使用它的好時機。MVC依賴注入

有誰能告訴我哪些DI工具現在支持MVC4,哪些現在提供最簡單的設置。由於項目很小,我的需求相當簡單。對我來說最重要的是一個易於學習和配置的系統。

回答

2

我不知道MVC 4(我還沒有機會玩它),但我會推薦Ninject作爲DI容器。你可能只在您的解決方案安裝Ninject MVC3項目(從的NuGet),它可能只是MVC4 工作,如果不使用:

DependencyResolver.SetResolver(new NinjectDependencyResolver(myKernal));  

其博客上講述這裏http://blogs.microsoft.co.il/blogs/gilf/archive/2010/10/17/dependency-injection-in-mvc-3-was-made-easier.aspx

博客文章適用爲了統一,但它與Ninject幾乎相同,實現了一個Dependancy Resolver來包裝ninject並將其放入global.ascx文件。

+1

您推薦ninject粘貼統一碼嗎? :)theres也unity.mvc3,但你必須具體告訴它,當你想要它通過使用分層生命時間管理器處置一個對象 – 2011-12-23 15:20:20

+0

該帖子更多圍繞如何使用任何與MVC3的DI容器,個人我使用的Webactivator提供的東西Ninject.Web.MVC3,但另一種選擇是使用內置的依賴解析器自己完成。我更新了代碼示例來說Ninject(但它實際上並沒有任何不同) – 2011-12-24 08:39:56

0

由於某些原因,使用NinjectDependencyResolver的Ninject對MVC4(Developer預覽版)無效。

我解決了它使用SetResolver的另一個重載取兩個匿名函數來解決依賴關係。

IKernel kernel = new StandardKernel();  
kernel.Bind<...>().To(...); 
DependencyResolver.SetResolver(t => kernel.Get(t), t => kernel.GetAll(t)); 
5

我在MVC 4 Beta項目中成功使用了Ninject.MVC3 NuGet包。

// Global.asax.cs 

public static void Configure(HttpConfiguration config) 
{ 
    var kernel = new StandardKernel(); 
    RegisterServices(kernel); 

    // For ApiControllers 
    config.ServiceResolver.SetResolver(
     t => kernel.TryGet(t), 
     t => kernel.GetAll(t)); 

    // For Controllers 
    DependencyResolver.SetResolver(
     t => kernel.TryGet(t), 
     t => kernel.GetAll(t)); 
} 

public static void RegisterServices(IKernel kernel) 
{ 
    kernel.Bind<IRepository>().To<Repository>(); 
} 

protected void Application_Start() 
{ 
    ... 

    Configure(GlobalConfiguration.Configuration); 
} 
+0

我剛剛發現,使用ServiceResolver.SetResolver可以正常工作,因爲對ApiController派生的控制器發出請求,但會導致「無參數構造函數爲此定義目的。」向Controller發出控制器請求時出錯。至於Jason Cornwall [在他的博客Twenty6上指出](http://twenty6-jc.blogspot.com/2012/02/idependencyresolver-and-aspnet-web-api.html),「ApiControllers的IDependencyResolver是一個完全不同的類型並在不同的解析器上「設置」。「 – Cory 2012-02-25 22:29:56

+0

如果您使用的是MVC 4 RC,請在另一個SO線程上查看[Michael Baird的回覆](http://stackoverflow.com/a/10855037/186778)。 – Cory 2012-07-09 21:37:11