十年網(wǎng)站開發(fā)經(jīng)驗 + 多家企業(yè)客戶 + 靠譜的建站團隊
量身定制 + 運營維護+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
IOC,是控制反轉(zhuǎn)(Inversion of Control)的英文簡寫, 控制反轉(zhuǎn)一般分為兩種類型,依賴注入(Dependency Injection)和依賴查找(Dependency Lookup)。依賴注入應(yīng)用比較廣泛。本文就簡單說說IOC在MVC中 的依賴注入的使用方法。
成都創(chuàng)新互聯(lián)公司主營鎮(zhèn)雄網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,成都APP應(yīng)用開發(fā),鎮(zhèn)雄h5重慶小程序開發(fā)公司搭建,鎮(zhèn)雄網(wǎng)站營銷推廣歡迎鎮(zhèn)雄等地區(qū)企業(yè)咨詢
我新建了一個mvc 項目在 HomeController 中這樣寫:

1 public DataService dataService { get; set; }2 3 public HomeController(DataService dataService)4 {5 this.dataService = dataService;6 }
其中 DataService類是我寫的一個提供數(shù)據(jù)的類:

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 GetData()11 {12 return repos.GetData();13 }14 15 } 
1 public interface IRepository2 {3 IEnumerable GetData();4 } 
1 public class DataRepository : IRepository 2 { 3 4 public DataRepository() 5 { 6 7 } 8 9 public IEnumerable GetData()10 {11 List list = new List();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 } 
然后運行項目,頁面會出現(xiàn)這樣一個結(jié)果:

報的錯是接口沒有注冊,導(dǎo)致構(gòu)造的時候出錯。怎么解決呢?IOC可以完美解決。
首先添加相關(guān)的類庫,右鍵 manager Nuget packages 搜索unity

添加以下兩個,之后會發(fā)現(xiàn)項目新加了一些東西:

然后我們就可以做IOC 依賴注入了,
在UnityConfig.cs中的 RegisterTypes方法中添加 一句
1 Container.RegisterType
其中IRepository 是我們要注入的構(gòu)造函數(shù)中參數(shù)的接口,而 DataRepository是這個接口的具體實現(xiàn)。
或者我這樣寫:
1 container.RegisterType(2 new InjectionConstructor(3 new ResolvedParameter ()4 ));
都是可以的。
這樣 我們就能正確的運行這個項目,
Action中的代碼:
1 public ActionResult Index()2 {3 IEnumerable list = dataService.GetData();4 return View(list);5 } View中:

1 @model IEnumerable2 @{ 3 ViewBag.Title = "Home Page"; 4 } 5 6 7 89 @foreach (var item in Model)10 {11
14- @item
12 }13

顯示的效果:
