IoC之Unity实现

public static class Bootstrapper
    {
        private static ILog logger = LogManager.GetLogger(typeof(Bootstrapper));

        static Bootstrapper()
        {
            try
            {
                logger.Info("start load container");
                Container.InitializeWith(new DependencyResolverFactory());
            }
            catch (Exception ex)
            {
                logger.Fatal(ex);
            }
        }
        public static void Run()
        {
            logger.Info("start run bootstrapper task...");
            Container.ResolveAll<IBackgroundTask>().ForEach(action =>
            {
                action.Start();
            });
        }
    }
public interface IDependencyResolverFactory
    {
        IDependencyResolver CreateInstance();
    }

public interface IDependencyResolver : IDisposable
    {
        void Register<T>(T instance);
        void Inject<T>(T existing);
        T Resolve<T>(Type type);
        T Resolve<T>(Type type, string name);
        T Resolve<T>();
        T Resolve<T>(string name);
        IEnumerable<T> ResolveAll<T>();
    }
public class DependencyResolverFactory : IDependencyResolverFactory
    {
        private static ILog logger = LogManager.GetLogger(typeof(DependencyResolverFactory));
        private static Dictionary<string, IDependencyResolver> dictDependency = new Dictionary<string, IDependencyResolver>();

        private readonly Type _resolverType;        

        public DependencyResolverFactory(string resolverTypeName)
        {
            _resolverType = Type.GetType(resolverTypeName, true, true);
        }

        public DependencyResolverFactory()
            : this(ConfigurationManager.AppSettings["dependencyResolverTypeName"])
        {
        }

        public IDependencyResolver CreateInstance()
        {
            try
            {
                if (dictDependency.ContainsKey(_resolverType.FullName))
                {
                    return dictDependency[_resolverType.FullName];
                }
                var instance = Activator.CreateInstance(_resolverType, new object[] {"" }) as IDependencyResolver;
                dictDependency.Add(_resolverType.FullName, instance);
                return instance;
            }
            catch (Exception exception)
            {
                logger.Error(exception);
            }
            return null;
        }
    }
public class UnityDependencyResolver : DisposableResource,IDependencyResolver
    {
        private readonly IUnityContainer container;

        private static object syncObject = new object();
        private static Dictionary<string, IUnityContainer> containers = new Dictionary<string, IUnityContainer>();

        public UnityDependencyResolver(IUnityContainer container)
        {
            this.container = container;
        }
        public UnityDependencyResolver(string containerName = ""):this(new UnityContainer().AddNewExtension<Interception>())
        {
            if (containers.ContainsKey(containerName))
            {
                this.container = containers[containerName];
            }
            else
            {
                lock (syncObject)
                {
                    UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
                    if (section == null)
                    {
                        throw new ConfigurationErrorsException("The Unity configuration section does not exist");
                    }
                    IUnityContainer con = new UnityContainer();
                    if (string.IsNullOrEmpty(containerName))
                    {
                        section.Configure(con);
                    }
                    else
                    {
                        section.Configure(con, containerName);
                    }

                    containers.Add(containerName, con);
                    this.container = containers[containerName];
                }
            }
        }

        public void Register<T>(T instance)
        {
            container.RegisterInstance(instance);
        }

        public void Inject<T>(T instance)
        {
            container.BuildUp(instance);
        }

        public T Resolve<T>(Type type)
        {
            return (T)container.Resolve(type);
        }

        public T Resolve<T>(Type type, string name)
        {
            return (T)container.Resolve(type, name);
        }

        public T Resolve<T>()
        {
            return container.Resolve<T>();
        }

        public T Resolve<T>(string name)
        {
            return container.Resolve<T>(name);
        }

        public IEnumerable<T> ResolveAll<T>()
        {
            return container.ResolveAll<T>();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                container.Dispose();
            }
            base.Dispose(disposing);
        }
    }
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
  </configSections>

  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration" />

    <!-- BackgroundTask -->
    <alias alias="IBackgroundTask" type="UnitySample.Core.Infrastructure.IBackgroundTask,UnitySample.Core"/>
    <alias alias="UserSettingBackgroundTask" type="UnitySample.Core.Infrastructure.UserSettingBackgroundTask,UnitySample.Core"/>

    <!-- Dao-->
    <alias alias="CacheDataDao" type="UnitySample.Core.Dao.CacheDataDao,UnitySample.Core"/>
    <alias alias="FunctionCatalogDao" type="UnitySample.Core.Dao.FunctionCatalogDao,UnitySample.Core"/>
    <alias alias="FunctionDao" type="UnitySample.Core.Dao.FunctionDao,UnitySample.Core"/>
    <alias alias="ConfigSettingDao" type="UnitySample.Core.Dao.ConfigSettingDao,UnitySample.Core"/>

    <!-- Cache -->
    <alias alias="ICache" type="UnitySample.Core.Infrastructure.Caching.ICache,UnitySample.Core"/>
    <alias alias="CacheImpl" type="UnitySample.Core.Infrastructure.Caching.CacheImpl,UnitySample.Core"/>

    <!-- db helper-->
    <alias alias="SQLiteHelper" type="UnitySample.Core.DataAccess.SQLiteHelper,UnitySample.Core" />

    <!-- config -->
    <alias alias="IConfigurationSettings" type="UnitySample.Core.Configuration.IConfigurationSettings,UnitySample.Core"/>
    <alias alias="ConfigurationSettings" type="UnitySample.Core.Configuration.ConfigurationSettings,UnitySample.Core"/>

    <alias alias="IEventAggregator" type="UnitySample.Core.Infrastructure.IEventAggregator,UnitySample.Core"/>
    <alias alias="EventAggregator" type="UnitySample.Core.Infrastructure.EventAggregator,UnitySample.Core"/>

    <container>
      <extension type="Interception" />

      <!-- BackgroundTask-->
      <register type="IBackgroundTask" mapTo="UserSettingBackgroundTask" name="UserSettingTask">
        <lifetime type="singleton"/>
        <constructor>
          <param name="eventAggregator" dependencyType="IEventAggregator" />
          <param name="configDao" dependencyType="ConfigSettingDao" />
        </constructor>
      </register>

      <!-- Cache -->
      <register type="ICache" mapTo="CacheImpl" name="MemoryCache">
        <lifetime type="singleton"/>
        <constructor>
          <param name="cacheManagerName" value="MemoryCache" />
        </constructor>
      </register>
      <register type="ICache" mapTo="CacheImpl" name="FileCache">
        <lifetime type="singleton"/>
        <constructor>
          <param name="cacheManagerName" value="FileCache" />
        </constructor>
      </register>
      <register type="ICache" mapTo="CacheImpl" name="CFPCache">
        <lifetime type="singleton"/>
        <constructor>
          <param name="cacheManagerName" value="CFPCache" />
        </constructor>
      </register>
      <register type="ICache" mapTo="CacheImpl" name="CFHCache">
        <lifetime type="singleton"/>
        <constructor>
          <param name="cacheManagerName" value="CFHCache" />
        </constructor>
      </register>
      <register type="ICache" mapTo="CacheImpl" name="CFSCache">
        <lifetime type="singleton"/>
        <constructor>
          <param name="cacheManagerName" value="CFSCache" />
        </constructor>
      </register>

      <!-- Dao -->
      <register type="CacheDataDao">
        <lifetime type="singleton"/>
        <constructor>
          <param name="db" dependencyType="SQLiteHelper" />
        </constructor>
      </register>

      <register type="FunctionCatalogDao">
        <lifetime type="singleton"/>
        <constructor>
          <param name="db" dependencyType="SQLiteHelper" />
        </constructor>
      </register>

      <register type="FunctionDao">
        <lifetime type="singleton"/>
        <constructor>
          <param name="db" dependencyType="SQLiteHelper" />
        </constructor>
      </register>

      <register type="ConfigSettingDao">
        <lifetime type="singleton"/>
        <constructor>
          <param name="db" dependencyType="SQLiteHelper" />
        </constructor>
      </register>
      <!-- DBHelper -->
      <register type="SQLiteHelper">
        <lifetime type="singleton" />
      </register>

      <!--config-->
      <register type="IConfigurationSettings" mapTo="ConfigurationSettings">
        <lifetime type="singleton"/>
        <constructor>
          <param name="configDao" dependencyType="ConfigSettingDao" />
          <param name="eventAggregator" dependencyType="IEventAggregator" />
        </constructor>
      </register>

      <register type="IEventAggregator" mapTo="EventAggregator">
        <lifetime type="singleton"/>
      </register>

    </container>
  </unity>
</configuration>

启动:

Bootstrapper.Run();

如果不用Unity,而采用其他IoC框架,只需实现IDependencyResolver,同时将App.config中dependencyResolverTypeName指向即可。

时间: 2024-10-13 01:34:24

IoC之Unity实现的相关文章

ASP.NET MVC IOC之Unity攻略

一.你知道IOC与DI吗? 1.IOC(Inversion of Control )——控制反转 即依赖对象不在被依赖模块的类中直接通过new来获取 先看看下面这段代码的问题~ public class SqlServerDal { public void Delete() { Console.WriteLine("删除表中某个订单信息!"); } } public class Order { private readonly SqlServerDal dal = new SqlSer

C# Ioc容器Unity,简单实用

原文:C# Ioc容器Unity,简单实用 开头先吐槽一下博客园超级不好用,添加图片后就写不动字了,难道是bug 好进入正题,先来说下依赖注入,简单来说就是定义好接口,上层代码调用接口,具体实现通过配置文件方式去指定具体实现类. 首先我们需要通过nuget来安装unity 安装好后就可以写一个方法类去实现依赖注入 public class UnityIocHelper : IServiceProvider { private readonly IUnityContainer _container

依赖反转Ioc和unity,autofac,castle框架教程及比较

1.依赖倒置的相关概念 http://www.cnblogs.com/fuchongjundream/p/3873073.html IoC模式(依赖.依赖倒置.依赖注入.控制反转) 2.依赖倒置的方式 http://www.cnblogs.com/muzinian/p/3357741.html 于依赖反转原则.控制反转和依赖注入的抽象的初学者指南 3.主流ioc框架 http://www.cnblogs.com/bchp/articles/1527693.html http://www.cnbl

IoC之Unity

一.什么是IcC? IoC(Inversion of Control,控制反转)又称“依赖注入”(Dependence Injection,DI). 控制反转就是创建对象的权利由开发人员控制,转为由容器来控制. 依赖注入就是通过容器创建对象的,是通过在构造方法的参数,属性设置和接口等方式注入的. IoC的基本概念是:不创建对象,但是描述创建它们的方式.在代码中不直接与对象和服务连接,但在配置文件(或程序)中描述创建关系,容器负责将它们联系起来. 二.什么是Unity? Unity是微软开发的一款

第十六回 IoC组件Unity续~批量动态为Unity添加类型和行为

回到目录 之前的一篇Unity的文章主要是基本的实现,并没有什么特别的地方,使用Unity可以方便的实现应用程序的IoC控制反转,这给我们的应用程序在耦合度上变得高了,同时可测试性加强了,当然,这些的前提都是面向接口编程,如果你面向了具体实现去写程序,那你不用再看本篇文章了,呵呵. 本文章主要分享一下,通过Unity组件里的服务定位器ServiceLocator来实现批量加载类型,即你不用那它们一个个的配置到config文件里了,甚至在进行动态加载时,同时可以为它添加一些行为,如缓存,呵呵 !

IOC实现-Unity

.NET中实现IOC有很多方式,比如:Unity.Ninject.Autofac.MEFNinject的实现参考<Pro ASP.NET MVC3.5 FrameWork>下面给出的是Unity的实现,结合配置文件实现的IOC.配置示例:<?xml version="1.0"?><configuration>    <configSections>        <section name="unity" typ

IOC使用Unity 实现依赖注入

转自:http://www.cnblogs.com/techborther/archive/2012/01/06/2313498.html http://www.cnblogs.com/xishuai/p/3728576.html http://www.cnblogs.com/artech/archive/2011/09/15/UnityDemo.html http://www.cnblogs.com/legendxian/archive/2010/01/08/1641366.html Asp.

[IoC容器Unity]第三回:依赖注入

上节介绍了,Unity的Lifetime Managers生命周期,Unity具体实现依赖注入包含构造函数注入.属性注入.方法注入,所谓注入相当赋值,下面一个一个来介绍. 2.构造函数注入 Unity利用Resolve方法解析一个对象,都是调用注册类型的构造函数来初始化的,初始化时,Unity能够控制初始化的值,当然,我们要给Unity提供足够的原料,要不然也是巧妇难无米之炊,下面看一些简单的示例. 先准备几个类如下: /// <summary> /// 班级接口 /// </summa

理解依赖注入(IOC)和学习Unity

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