IOC实现-Unity

Posted zhaow

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IOC实现-Unity相关的知识,希望对你有一定的参考价值。

.NET中实现IOC有很多方式,比如:Unity、Ninject、Autofac、MEF
Ninject的实现参考《Pro ASP.NET MVC3.5 FrameWork》
下面给出的是Unity的实现,结合配置文件实现的IOC。
配置示例:
<?xml version="1.0"?>
<configuration>
    <configSections>
        <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration"/>
    </configSections>
    <unity>
        <typeAliases>
            <!--管理对象生命周期的三种方式-->
            <!--创建单例实例-->
            <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
            <!--只可以保持对象的弱引用-->
            <typeAlias alias="external" type="Microsoft.Practices.Unity.ExternallyControlledLifetimeManager, Microsoft.Practices.Unity" />
            <!--在同一个线程返回同一个对象实例,不同线程对象实例不相同 -->
            <typeAlias alias="perThread" type="Microsoft.Practices.Unity.PerThreadLifetimeManager, Microsoft.Practices.Unity" />
            
            <!--别名-->
            <typeAlias alias="ICustomerInfo" type="Yintai.ERP.Service.Customer.Interface.ICustomerInfo,Yintai.ERP.Service.Customer.Interface" />
            <typeAlias alias="CustomerInfo" type="Yintai.ERP.Service.CustomerInfo.CustomerInfoService,Yintai.ERP.Service.CustomerInfo" />
        </typeAliases>
        <containers>
            <container name="ContainerService">
                <!--注册类型-->
                <register type="ICustomerInfo" mapTo="CustomerInfo">
                    <lifetime type="singleton"/>
                </register>
            </container>
        </containers>
    </unity>
</configuration>

C#代码:
private ICSWorkBusiness cSWorkBusiness=null;
/// <summary>
/// 构造函数
/// </summary>
public CSWorkService()
{
     cSWorkBusiness=ServiceBusContainer.Instance.Container.Resolve<ICSWorkBusiness>();
}

更多阅读资料:
微软企业库Unity学习笔记(一):http://www.cnblogs.com/rush/archive/2011/02/12/EntlibUnity.html
微软企业库Unity学习笔记(二):http://www.cnblogs.com/rush/archive/2011/04/16/Unity.html

补充2017-8-8:
InjectionConstructor --构造函数注入(多重载构造函数)
InjectionMethod --方法注入
Dependency --属性注入
Dependency(“name”) --给属性命名

项目中的代码结构:

技术分享图片

指定类型:
技术分享图片

配置映射关系:
技术分享图片

应用层==》
定义IOC容器:
技术分享图片
容器代码:
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace Wede.ERP.Service.CRM
{

    public sealed class CRMServiceContainer
    {
        private static CRMServiceContainer _instance;
        private string configFile = "";
        private string _ContainerName = "ContainerService";
        static readonly object lockobj = new object();
        private static IUnityContainer crmServiceUnityContainer;

        /// <summary>
        /// 构造函数,得到Unit配置文件
        /// </summary>
        private CRMServiceContainer()
        {
            configFile = Wede.ERP.Config.BaseConfig.GetServiceCrmUnityConfigPath;
            if (string.IsNullOrEmpty(configFile))
            {
                throw new Exception(Wede.ERP.Config.BaseConfig.ErrorMessage);
            }
            else
            {
                configFile = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,configFile);
            }
        }

        /// <summary>
        /// 单例方式实例化
        /// </summary>
        public static CRMServiceContainer Instance
        {
            get
            {
                lock (lockobj)
                {
                    if (_instance == null)
                    {
                        _instance = new CRMServiceContainer();
                    }
                    return _instance;
                }
            }
        }
        private object lockObj = new object();
        /// <summary>
        /// 初始化Unity的IoC容器对象
        /// </summary>
        public IUnityContainer Container
        {
            get
            {
                if (crmServiceUnityContainer == null)
                {
                    lock (lockObj)
                    {
                        crmServiceUnityContainer = new UnityContainer();
                        ExeConfigurationFileMap basicFileMap = new ExeConfigurationFileMap
                        {
                            ExeConfigFilename = configFile
                        };
                        UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager
                            .OpenMappedExeConfiguration(basicFileMap, ConfigurationUserLevel.None)
                            .GetSection("unity");
                        section.Configure(crmServiceUnityContainer, _ContainerName);
                    }
                }
                return crmServiceUnityContainer;
            }
        }
        public T Resolve<T>()
        {
            return Container.Resolve<T>();
        }
    }
}
应用层==》服务层应用:
技术分享图片

以上是关于IOC实现-Unity的主要内容,如果未能解决你的问题,请参考以下文章

Unity 处理IOC AOP

Unity IOC容器通过配置实现类型映射的几种基本使用方法

Unity-IOC

Unity-IOC

Unity-IOC

Unity-IOC