IoC之Unity实现_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > IoC之Unity实现

IoC之Unity实现

 2014/11/17 3:06:46  ?王浩?  程序员俱乐部  我要评论(0)
  • 摘要:publicstaticclassBootstrapper{privatestaticILoglogger=LogManager.GetLogger(typeof(Bootstrapper));staticBootstrapper(){try{logger.Info("startloadcontainer");Container.InitializeWith(newDependencyResolverFactory());}catch(Exceptionex){logger.Fatal(ex)
  • 标签:实现

 

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指向即可。

 

发表评论
用户名: 匿名