.Net IOC框架入门之一 Unity

一、概述

  IOC:英文全称:Inversion of Control,中文名称:控制反转,它还有个名字叫依赖注入(Dependency Injection)。
  作用:将各层的对象以松耦合的方式组织在一起,解耦,各层对象的调用完全面向接口。当系统重构的时候,代码的改写量将大大减少。
  依赖注入: 当一个类的实例需要另一个类的实例协助时,在传统的程序设计过程中,通常有调用者来创建被调用者的实例。然而采用依赖注入的方式,创建被调用者的工作不再由调用者来完成,因此叫控制反转,创建被调用者的实例的工作由IOC容器来完成,然后注入调用者,因此也称为依赖注入。

   Unity是微软Patterns & Practices团队所开发的一个轻量级的,并且可扩展的依赖注入(Dependency Injection)容器;

  它支持常用的三种依赖注入方式:构造器注入(Constructor Injection)、属性注入(Property Injection),以及方法调用注入(Method Call Injection)。

  现在Unity最新的版本的4.0版,可以在微软的开源站点 https://github.com/unitycontainer/unity 下载最新的发布版本。

  通过使用Unity,我们能轻松构建松耦合结构的程序,从而让整个程序框架变得清晰和易于维护。

二、简单示例

  创建一个mvc5项目 Web.Mvc,然后在创建一个Business类库,将类库添加引用到Web.Mvc项目.

Business类库

  类库代码

  a、Business类库定义一个接口IUserService

namespace Business
{
    /// <summary>
    /// 显示信息
    /// </summary>
    public interface IUserService
    {
        string Display(string mes);
    }
}

  b、Business类库实现接口

namespace Business
{
    public class UserService : IUserService
    {
        /// <summary>
        /// 显示信息
        /// </summary>
        /// <param name="mes"></param>
        public string Display(string mes)
        {
            return "I say:" + mes;
        }
    }
}

 

示例一

  在Web.Mvc项目通过nuget添加unity.mvc5 (1.2.3)

   1.注册服务

  注册依赖使用依赖注入生效,在Web.Mvc项目的Global.asax进行注册 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Business;
using Microsoft.Practices.Unity;
using Unity.Mvc5;

namespace Web.Mvc
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //注入 Ioc
            var container = this.BuildUnityContainer();
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }


        IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();
            container.RegisterType<IUserService, UserService>();
            return container;
        }
    }
}

  2.注入服务

namespace Web.Mvc.Controllers
{
    public class HomeController : Controller
    {

        private IUserService userService;

        public HomeController(IUserService userService)
        {
            this.userService = userService;
        }

        public ActionResult Index()
        {
            ViewBag.Msg = userService.Display("hahaha");
            return View();
        }
   }
}

e、在Index.cshtml找个地方写入@ViewBag.Msg 就可以,如

<h1>ASP.NET - @ViewBag.Msg</h1>

最后运行项目,实现效果

ASP.NET - I say:hahaha

示例二

  本示例为2017.12.08补充。

  创建一个mvc5项目 Web.Mvc,然后在创建一个Business类库,将类库添加引用到Web.Mvc项目,在Web.Mvc项目通过nuget添加unity.mvc5 (1.3.0)

  命令:Install-Package Unity.Mvc5 -Version 1.3.0

  安装后如图

  

  1. 调用注册组件

  在Global.asax.cs 的Application_Start 方法添加 UnityConfig.RegisterComponents() ,MVC会使用 Unity.Mvc5的 DependencyResolver去解析服务

protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            UnityConfig.RegisterComponents();//在此处添加
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
           
        }

  2.注册服务

  找到App_Start下的UnityConfig类,如下修改

 public static class UnityConfig
    {
        public static void RegisterComponents()
        {
            var container = new UnityContainer();

            //在这里使用container注册所有服务
            container.RegisterType<IUserService, UserService>();//自定义的服务

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }
    }

  3.修改控制器Home和页面Index

  

public class HomeController : Controller
    {
        private IUserService userService;

        public HomeController(IUserService userService)
        {
            this.userService = userService;
        }

        public ActionResult Index()
        {
            ViewBag.Name = userService.Display("我是 UNITY 1.3.0");
            return View();
        }

页面代码

<div class="jumbotron">
    <h1>Unity 入门</h1>
    <p class="lead">@ViewBag.Name</p> 
</div>
 

效果

 

三、注册封装

对示例一 的注册进行独立封装到BootStrapper中

c、注册依赖使用依赖注入生效

在Web.Mvc项目的Global.asax进行注册 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Business;
using Microsoft.Practices.Unity;
using Unity.Mvc5;

namespace Web.Mvc
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //注入 Ioc 
            BootStrapper.Initialise();
        } 
    }
}

BootStrapper代码

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Business;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using Unity.Mvc5;

namespace Web.Mvc
{
    public class BootStrapper
    {
        /// <summary>
        /// 获取容器-注册依赖关系
        /// </summary>
        /// <returns></returns>
        public static IUnityContainer Initialise()
        {
            var container = BulidUnityContainer();
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
            return container;
        }

        /// <summary>
        /// 加载容器
        /// </summary>
        /// <returns></returns>
        private static IUnityContainer BulidUnityContainer()
        {
            var container = new UnityContainer();
            RegisterTypes(container);
            return container;
        }

        /// <summary>
        /// 实施依赖注入
        /// </summary>
        /// <param name="container"></param>
        private static void RegisterTypes(IUnityContainer container)
        { 
            //类型的配置容器注册
            container.RegisterType<IUserService, UserService>();
            //container.RegisterType<IUserService, UserService>(new ContainerControlledLifetimeManager());//通过生命周期实现了单例模式

            //已有对象实例的配置容器注册,也为单例
            //UserService userService = new UserService(); 
            //container.RegisterInstance<IUserService>(userService);

        }
    }
}

Unity注册配置

 修改上面的方法,将注册放到配置文件中

1.方法修改

        /// <summary>
        /// 实施依赖注入
        /// </summary>
        /// <param name="container"></param>
        private static void RegisterTypes(IUnityContainer container)
        {
            ////依赖关系可以选择代码形式,也可以用配置文件的形式
            UnityConfigurationSection config = (UnityConfigurationSection)ConfigurationManager.GetSection(UnityConfigurationSection.SectionName);
            config.Configure(container, "defaultContainer"); 
        }
UnityConfigurationSection.SectionName为unity

2.配置文件

 提示:自定义web.config节点来实现

<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration"/>
    <!-- 一般将unity节点放到文件末尾 --> 
  </configSections> 
  
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <namespace name="Business" />
    <assembly name="Business" />
    <containers>
      <container name="defaultContainer">
        <register type="IUserService" mapTo="UserService">
          <lifetime type="singleton" />
        </register>
        <register type="ILocalUserService" mapTo="LocalUserService"/>
      </container>
    </containers>
  </unity>
</configuration>

或者为

直接指定命名空间

  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> 
    <assembly name="Business" />
    <containers>
      <container name="defaultContainer">
        <register type="Business.IUserService" mapTo="Business.UserService">
          <lifetime type="singleton" />
        </register>
        <register type="Business.ILocalUserService" mapTo="Business.LocalUserService"/>
      </container>
    </containers>
  </unity>

或者为

指定程序集名称

  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">  
    <containers>
      <container name="defaultContainer">
        <register type="Business.IUserService,Business" mapTo="Business.UserService,Business">
          <lifetime type="singleton" />
        </register>
        <register type="Business.ILocalUserService,Business" mapTo="Business.LocalUserService,Business"/>
      </container>
    </containers>
  </unity>

 

 源码下载:https://gitee.com/zmsofts/XinCunShanNianDaiMa/blob/master/IocDemo.rar

 

参考网址:

http://www.cnblogs.com/zhangchenliang/archive/2013/01/08/2850970.html

https://www.lanhusoft.com/Article/108.html

http://blog.csdn.net/xingxing513234072/article/details/21176247

http://www.cnblogs.com/wwj1992/p/6728370.html

http://www.cnblogs.com/xishuai/p/3670292.html(推荐)

 

posted @ 2017-08-19 11:02  心存善念  阅读(4042)  评论(1编辑  收藏  举报