今天主要来讲解使用Unity来自动注入。Unity前面我们已经详细的介绍过了,如有需要请自行前往去看,今天我们的重点是说MVC与IOC的结合。

IOC:控制反转,控制反转的工具是DI(依赖注入:构造函数注入--属性注入--方法注入(按时间顺序)),DI使用的工具是Unity容器。

一:新增mvc项目,然后nuget添加引用

   <package id="Unity" version="5.10.3" targetFramework="net45" />
<package id="Unity.Abstractions" version="4.1.3" targetFramework="net45" />
<package id="Unity.Configuration" version="5.10.0" targetFramework="net45" />
<package id="Unity.Container" version="5.10.3" targetFramework="net45" />
<package id="Unity.Interception" version="5.10.1" targetFramework="net45" />
<package id="Unity.Interception.Configuration" version="5.10.0" targetFramework="net45" />

二:新增文件夹CfgFiles新增一个unity.config文件,具体代码和注释如下:

 <configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Unity.Configuration"/>
</configSections>
<unity>
<sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Unity.Interception.Configuration"/>
<containers>
<container name="ruanmouContainer">
<extension type="Interception"/>
<!--<register type="命名空间.接口类型2,程序集" mapTo="命名空间.实现类型2,程序集" />-->
<register type="System.Data.Entity.DbContext, EntityFramework" mapTo="Ruanmou.EF.Model.JDDbContext, Ruanmou.EF.Model"/> <register type="Ruanmou.Bussiness.Interface.IUserCompanyService,Ruanmou.Bussiness.Interface" mapTo="Ruanmou.Bussiness.Service.UserCompanyService, Ruanmou.Bussiness.Service">
<interceptor type="InterfaceInterceptor"/>
</register> <register type="Ruanmou.Bussiness.Interface.IUserService,Ruanmou.Bussiness.Interface" mapTo="Ruanmou.Bussiness.Service.UserService, Ruanmou.Bussiness.Service">
<interceptor type="InterfaceInterceptor"/>
<interceptionBehavior type="Ruanmou.Project.AOP.LogBeforeBehavior, Ruanmou.MVC5"/>
<interceptionBehavior type="Ruanmou.Project.AOP.LogAfterBehavior, Ruanmou.MVC5"/>
</register> <register type="Ruanmou.Bussiness.Interface.ICompanyService,Ruanmou.Bussiness.Interface" mapTo="Ruanmou.Bussiness.Service.CompanyService, Ruanmou.Bussiness.Service">
<interceptor type="InterfaceInterceptor"/>
</register>
</container>
</containers>
</unity>
</configuration>

需要注意的是:

1:一定在unity.config的属性中设置:复制到输出目录一定要设置:始终复制,这样做的目的是每次重新生成,会把这个untiy.config文件copy到bin目录下面。保证每次都是使用的是最新的。

2:下面这两个类是AOP拦截器需要的,如果需要的话则新增这些实体类,不需要的则直接删除掉。

<interceptionBehavior type="Ruanmou.Project.AOP.LogBeforeBehavior, Ruanmou.MVC5"/>
<interceptionBehavior type="Ruanmou.Project.AOP.LogAfterBehavior, Ruanmou.MVC5"/>

三:新增读取unity.config配置文件类DIFactory,代码如下:

  public class DIFactory
{
private static IUnityContainer container = null;
static DIFactory()
{
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "CfgFiles\\Unity.Config");
Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
UnityConfigurationSection section = (UnityConfigurationSection)configuration.GetSection(UnityConfigurationSection.SectionName);
container = new UnityContainer();
section.Configure(container, "ruanmouContainer");
} public static IUnityContainer GetContainer()
{
return container;
}
}

四:新增defaultController类的子类DIControllerFactory来进行重新,具体代码如下:

 public class DIControllerFactory : DefaultControllerFactory
{
private Logger logger = new Logger(typeof(DIControllerFactory)); protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
this.logger.Warn($"{controllerType.Name}被构造..."); IUnityContainer container = DIFactory.GetContainer();
//return base.GetControllerInstance(requestContext, controllerType);
return (IController)container.Resolve(controllerType);
}
}

五:在Global.asax中指定控制器为当前新增的控制器DIControllerFactory,代码如下:

  public class MvcApplication : System.Web.HttpApplication
{
private Logger logger = new Logger(typeof(MvcApplication));
protected void Application_Start()
{ AreaRegistration.RegisterAllAreas();//注册区域
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);//注册全局的Filter
RouteConfig.RegisterRoutes(RouteTable.Routes);//注册路由
BundleConfig.RegisterBundles(BundleTable.Bundles);//合并压缩 ,打包工具 Combres ControllerBuilder.Current.SetControllerFactory(new DIControllerFactory()); this.logger.Info("网站启动了。。。");
}
}

六:上面的准备工作已经做好了,下面来测试使用:

   public class ThirdController : Controller
{
private IUserService _iUserService = null;
private ICompanyService _iCompanyService = null;
private IUserCompanyService _iUserCompanyService = null;
/// <summary>
/// 构造函数注入---控制器得是由容器来实例化
/// </summary>
/// <param name="userService"></param>
/// <param name="companyService"></param>
/// <param name="userCompanyService"></param>
public ThirdController(IUserService userService, ICompanyService companyService, IUserCompanyService userCompanyService)
{
this._iUserService = userService;
this._iCompanyService = companyService;
this._iUserCompanyService = userCompanyService; } // GET: Third
public ActionResult Index()
{
IUserService service = this._iUserService;
User user = service.Find<User>();
return View();
}
}

通过以上6个步骤则完成了IOC与MVC的完美结合,以后不用每次在new 一个业务类了。可以在初始化控制器的时候进行初始化那些业务类。

c# MVC5(二) MVC与IOC结合的更多相关文章

  1. velocity+spring mvc+spring ioc+ibatis初试感觉(与struts+spring+hibernate比较)

    velocity+spring mvc+spring ioc+ibatis框架是我现在公司要求采用的,原因是因为阿里巴巴和淘宝在使用这样的框架,而我公司现在还主要是以向阿里巴巴和淘宝输送外派人员为 主 ...

  2. ASP.NET MVC使用IoC

    也许你会问ASP.NET MVC为什么会爱上IoC? 相爱的理由常常很简单,就像一首歌中所唱——“只为相遇那一个眼神”. 而ASP.NET MVC爱上IoC只为IoC能实现MVC控制器的依赖注入. 下 ...

  3. ASP.NET MVC 使用 IOC框架 AutoFac 自动释放数据库资源

    每次使用using或者dispose来释放资源会比较麻烦,作为一个会偷懒的程序员来说当然不能接受了. 一.引用 autofac.dll和autofac.integration.mvc.dll 二.打开 ...

  4. 攻城狮在路上(贰) Spring(二)--- Spring IoC概念介绍

    一.IoC的概念: IoC(控制反转)是Spring容器的核心.另一种解释是DI(依赖注入),即让调用类对某一个接口的依赖关系由第三方注入,以移除调用类对某一个接口实现类的一览. 定义如此,由此可见, ...

  5. ioc初步理解(一) 简单实用autofac搭建mvc三层+ioc(codeFirst)

    1]首先搭好框架 1.1]搭建ui层 1.2]创建其他内库文件 整个项目基本部分搭建完毕之后如下 2]使用nuget引用文件 先在每一个项目中引入ef 然后再UI层引入以下两个文件autofac和Au ...

  6. 请简要介绍Sping MVC、IoC和AOP

    Sping MVC是在Spring框架上发展起来的框架,它提供了构建Web应用程序的全功能MVC模块,使用了Spring可插入的MVC架构,可以自由的选择各个模块所使用的架构,非常灵活.Spring ...

  7. Spring系列(二):Spring IoC/DI的理解

    这几天重新学习了一下Spring,在网上找了相关的ppt来看,当看到Spring IoC这一章节的时候,先大致浏览了一下内容,有将近50页的内容,内心窃喜~QAQ~,看完这些内容能够对IoC有更深层次 ...

  8. MVC 使用IOC实现

    实现步骤: 1. 实现IDependencyResolver接口并通过DependencyResolver.SetResolver告知MVC,将部分类型实例解析工作交由IoC容器来处理: using ...

  9. Spring Framework 官方文档学习(二)之IoC容器与bean lifecycle

    到目前为止,已经看了一百页.再次感慨下,如果想使用Spring,那可以看视频或者找例子,但如果想深入理解Spring,最好还是看官方文档. 原计划是把一些基本接口的功能.层次以及彼此的关系罗列一下.同 ...

随机推荐

  1. NOIP 2002 产生数

    洛谷 P1037 产生数 https://www.luogu.org/problemnew/show/P1037 JDOJ 1298: [NOIP2002]产生数 T3 https://neooj.c ...

  2. public.js

    //通过id名称获取元素对象 function getid(idName){ return document.getElementById(idName); } //随机获取min-max的随机整数 ...

  3. shell 脚本 for,while,case 语句详解及案例

    ################for循环语句的结构#############使用for循环语句时,需要指定一个变量及可能的取值列表,针对每个不同的取值重复执行相同的命令序列,直到变量值用完退出循环. ...

  4. log4j输出到控制台的性能问题

    一.背景 最近几个业务遇到服务假死的情况,通过排查,我们发现是因为业务在线上使用了日志框架的ConsoleAppender所致. 请尊重作者劳动成果,转载请标明原文链接:https://www.cnb ...

  5. 算法&设计模式

    这里更新Python 算法&设计模式部分的博客(或目录链接)

  6. bower安装教程

    进入node.js官网下载相应操作系统的安装文件http://www.nodejs.org/download/ ,windows环境下载msi文件即可 打开下载的文件,一直点击下一步,完成安装 安装完 ...

  7. 企业级Nginx负载均衡与keepalived高可用实战(二)keepalived篇

    1.Keepalived高可用软件 1.1.Keepalived介绍 Keepalived软件起初是专门为LVS负载均衡软件设计的,用来管理并监控LVS集群系统中各个服务节点的状态,后来又加入了可以实 ...

  8. 开源组件websocket-sharp中基于webapi的httpserver使用体验

    一.背景 因为需要做金蝶ERP的二次开发,金蝶ERP的开放性真是不错,但是二次开发金蝶一般使用引用BOS.dll的方式,这个dll对newtonsoft.json.dll这个库是强引用,必须要用4.0 ...

  9. pgsql 的函数

    因为pgsql中没有存储过程和包,所以类似功能通过函数来实现 PostgreSQL的存储过程简单入门 http://blog.csdn.net/rachel_luo/article/details/8 ...

  10. tmp/ccdLyHub.o:(.eh_frame+0x12): undefined reference to `__gxx_personality_v0' collect2: ld returned 1 exit status

    其实就是一个问题,gcc只能编译.c文件,你如果取名为.cpp,那么gcc编译就会就会出现这个错误. 这种情况下: 1.用g++编译(.c 或.c++都可以编译) 2.仍用gcc编译,但是文件后缀改为 ...