ASP.NET MVC* 采用Unity依赖注入Controller

Unity是微软Patterns & Practices团队所开发的一个轻量级的,并且可扩展的依赖注入(Dependency Injection)容器,它支持常用的三种依赖注入方式:构造器注入(Constructor Injection)、属性注入(Property Injection),以及方法调用注入(Method Call Injection).可以在微软的开源站点http://unity.codeplex.com下载最新的发布版本和文档。通过使用Unity,我们能轻松构建松耦合结构的程序,从而让整个程序框架变得清晰和易于维护。

本文为了自己方便记录,如有不对欢迎指出

1、首先建立接口

 1 namespace IServices
 2 {
 3 
 4     public interface ISchool
 5     {
 6        
 7         List<string> GetSchoolList();
 8         string GetSchoolName();
 9     }
10 }

2、建立实现类

 1 namespace ServicesSchool
 2 {
 3     /// <summary>
 4     /// 
 5     /// </summary>
 6     public class School : ISchool
 7     {
 8         public List<string> GetSchoolList()
 9         {
10             return new List<string>() { 
11             "红旗小学","大兴小学"
12             };
13             
14         }
15         public string GetSchoolName()
16         {
17             return "红旗小学";
18         }
19     }
20 }

3、Controller实现

 1 namespace MVCWCF.Controllers
 2 {
 3     public class HomeController : Controller
 4     {
 5         private IServices.ISchool _school;
 6         public HomeController(IServices.ISchool school)
 7         {
 8             this._school = school;
 9         }
10         public string Index()
11         {
12             ViewBag.Message = "欢迎使用 ASP.NET MVC!";
13 
14 
15 
16             return _school.GetSchoolName();
17         }
18 
19         public ActionResult About()
20         {
21             return View();
22         }
23     }
24 }

4、Global.asax文件中进行注入

 1   protected void Application_Start()
 2         {
 3             AreaRegistration.RegisterAllAreas();
 4 
 5             RegisterGlobalFilters(GlobalFilters.Filters);
 6             RegisterRoutes(RouteTable.Routes);
 7 
 8             RouteTable.Routes.Add(new ServiceRoute("Uap", new WebServiceHostFactory(), typeof(ServicesSchool.School)));
 9 
10 
11 
12             //注入 Ioc  
13             var container = this.BuildUnityContainer();
14             DependencyResolver.SetResolver(new UnityDependencyResolver(container));  
15         }
16 
17         IUnityContainer BuildUnityContainer()
18         {
19             var container = new UnityContainer();
20             container.RegisterType<IServices.ISchool, ServicesSchool.School>();
21             return container;
22         } 

5、使用nuget为项目增加Unity相关的包

选中mvc的那个项目右键“管理NuGet 程序包”在弹出的窗口中输入Unity搜索,在结果选中Unity.MVC*点击安装。

原文地址:https://www.cnblogs.com/happygx/p/9227853.html