IOC 在Mvc中的使用

來源:互聯網
上載者:User

標籤:

    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 IRepository2     {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>

顯示的效果:

當然你也可以嘗試多個參數的注入。方法都是一樣的。

IOC 在Mvc中的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.