IOC,是控制反轉(Inversion of Control)的英文簡寫, 控制反轉一般分為兩種類型,依賴注入(Dependency Injection)和依賴查找(Dependency Lookup)。依賴注入應用比較廣泛。本文就簡單說說IOC在MVC中 的依賴注入的使用方法。
我新建了一個mvc 項目在 HomeController 中這樣寫:
1 public DataService dataService { get; set; } 2 3 public HomeController(DataService dataService) 4 { 5 this.dataService = dataService; 6 }
其中 DataService類是我寫的一個提供數據的類:
1 public class DataService 2 { 3 private IRepository repos { get; set; } 4 5 public DataService(IRepository repo) 6 { 7 repos = repo; 8 } 9 10 public IEnumerable<string> GetData() 11 { 12 return repos.GetData(); 13 } 14 15 }
1 public interface IRepository 2 { 3 IEnumerable<string> GetData(); 4 }
1 public class DataRepository : IRepository 2 { 3 4 public DataRepository() 5 { 6 7 } 8 9 public IEnumerable<string> GetData() 10 { 11 List<string> list = new List<string>(); 12 list.Add("test1"); 13 list.Add("test2"); 14 list.Add("test3"); 15 list.Add("test4"); 16 list.Add("test5"); 17 list.Add("test6"); 18 return list; 19 } 20 }
然后運行項目,頁面會出現這樣一個結果:
報的錯是接口沒有注冊,導致構造的時候出錯。怎么解決呢?IOC可以完美解決。
首先添加相關的類庫,右鍵 manager Nuget packages 搜索unity
添加以下兩個,之后會發現項目新加了一些東西:
然后我們就可以做IOC 依賴注入了,
在UnityConfig.cs中的 RegisterTypes方法中添加 一句
1 container.RegisterType<IRepository, DataRepository>();
其中IRepository 是我們要注入的構造函數中參數的接口,而 DataRepository是這個接口的具體實現。
或者我這樣寫:
1 container.RegisterType<DataService>( 2 new InjectionConstructor( 3 new ResolvedParameter<DataRepository>() 4 ));
都是可以的。
這樣 我們就能正確的運行這個項目,
Action中的代碼:
1 public ActionResult Index() 2 { 3 IEnumerable<string> list = dataService.GetData(); 4 return View(list); 5 }
View中:
1 @model IEnumerable<string> 2 @{ 3 ViewBag.Title = "Home Page"; 4 } 5 6 7 <div class="row"> 8 <ul> 9 @foreach (var item in Model) 10 { 11 <li>@item</li> 12 } 13 </ul> 14 </div>
顯示的效果:
當然你也可以嘗試多個參數的注入。方法都是一樣的。