IOC 在Mvc中的使用

时间:2023-03-08 18:53:31
IOC 在Mvc中的使用

IOC 在Mvc中的使用

IOC,是控制反转(Inversion of Control)的英文简写, 控制反转一般分为两种类型,依赖注入(Dependency Injection)和依赖查找(Dependency Lookup)。依赖注入应用比较广泛。本文就简单说说IOC在MVC中 的依赖注入的使用方法。

我新建了一个mvc 项目在 HomeController 中这样写:

IOC 在Mvc中的使用
1         public DataService dataService { get; set; }
2
3 public HomeController(DataService dataService)
4 {
5 this.dataService = dataService;
6 }
IOC 在Mvc中的使用

其中 DataService类是我写的一个提供数据的类:

IOC 在Mvc中的使用
 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 }
IOC 在Mvc中的使用
1   public interface IRepository
2 {
3 IEnumerable<string> GetData();
4 }
IOC 在Mvc中的使用
 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 在Mvc中的使用

然后运行项目,页面会出现这样一个结果:

IOC 在Mvc中的使用

报的错是接口没有注册,导致构造的时候出错。怎么解决呢?IOC可以完美解决。

首先添加相关的类库,右键 manager Nuget packages 搜索unity

IOC 在Mvc中的使用

添加以下两个,之后会发现项目新加了一些东西:

IOC 在Mvc中的使用     IOC 在Mvc中的使用

然后我们就可以做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中:

IOC 在Mvc中的使用
 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中的使用

显示的效果:

IOC 在Mvc中的使用

当然你也可以尝试多个参数的注入。方法都是一样的。