• Unity(四)IocContainer 封装类库


    首先要在项目中安装Unity,通过NuGet搜索Unity。

    1.定义接口 IDependencyResolver

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace IOCContainer
    {
        public interface IDependencyResolver : IDisposable
        {
            /// <summary>
            /// 注册 T类型实例
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="instance"></param>
            void Register<T>(T instance);
    
            /// <summary>
            /// 注入 
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="existing"></param>
            void Inject<T>(T existing);
    
            /// <summary>
            /// 解析
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="type"></param>
            /// <returns></returns>
            T Resolve<T>(Type type);
    
            T Resolve<T>(Type type, string name);
    
            T Resolve<T>();
    
            T Resolve<T>(string name);
    
            IEnumerable<T> ResolveAll<T>();
        }
    }
    

      

    2.具体实现接口 UnityDependencyResolver

    using Microsoft.Practices.Unity;
    using Microsoft.Practices.Unity.Configuration;
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Configuration;
    using System.Diagnostics;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace IOCContainer
    {
        [Serializable]
        public class UnityDependencyResolver : IDisposable, IDependencyResolver
        {
            //注入容器
            private IUnityContainer _container;
    
            public UnityDependencyResolver() : this(new UnityContainer())
            {
                UnityConfigurationSection configuration = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
                _container.LoadConfiguration(configuration, "UnityContainer");
            }
    
            public UnityDependencyResolver(IUnityContainer container)
            {
                _container = container;
            }
    
            public void Register<T>(T instance)
            {
                //注册实例
                _container.RegisterInstance(instance);
            }
    
            public void Inject<T>(T existing)
            {
                //注入加载
                _container.BuildUp(existing);
            }
    
            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>()
            {
                //解析容器中所有
                IEnumerable<T> namedInstances = _container.ResolveAll<T>();
                T unnamedInstance = default(T);
    
                try
                {
                    unnamedInstance = _container.Resolve<T>();
                }
                catch (ResolutionFailedException)
                {
                    //When default instance is missing
                }
    
                if (Equals(unnamedInstance, default(T)))
                {
                    return namedInstances;
                }
    
                return new ReadOnlyCollection<T>(new List<T>(namedInstances) { unnamedInstance });
            }
    
            public void Dispose()
            {
                if (_container != null)
                {
                    _container.Dispose();
                }
            }
        }
    }
    

      

    3.定义工厂接口 IDependencyResolverFactory

    using IOCContainer;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace IOCContainer
    {
        public interface IDependencyResolverFactory
        {
            /// <summary>
            /// 创建IDependencyResolver的实例
            /// </summary>
            /// <returns></returns>
            IDependencyResolver CreateInstance();
        }
    }
    

      

    4.具体实现工厂接口 DependencyResolverFactory

    using IOCContainer;
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace IOCContainer
    {
        public class DependencyResolverFactory : IDependencyResolverFactory
        {
            private Type _resolverType;
    
            public DependencyResolverFactory(string resolverTypeName)
            {
                _resolverType = Type.GetType(resolverTypeName, true, true);
            }
    
            public DependencyResolverFactory()
            {
                _resolverType = Type.GetType(ConfigurationManager.AppSettings["DependencyResolverTypeName"], true, true);
            }
    
            public IDependencyResolver CreateInstance()
            {
                //根据类型创建实例对象
                return Activator.CreateInstance(_resolverType) as IDependencyResolver;
            }
        }
    }
    

      

    5.调用工厂封装 IoC

    using IOCContainer;
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace IOCContainer
    {
        public static class IoC
        {
            //解析器
            private static IDependencyResolver _resolver;
    
            /// <summary>
            /// 初始化,创建实例对象
            /// </summary>
            /// <param name="factory"></param>
            [DebuggerStepThrough]
            public static void InitializeWith(IDependencyResolverFactory factory)
            {
                _resolver = factory.CreateInstance();
            }
    
            /// <summary>
            /// 注册对象
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="instance"></param>
            [DebuggerStepThrough]
            public static void Register<T>(T instance)
            {
                _resolver.Register(instance);
            }
    
            /// <summary>
            /// 注入对象
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="existing"></param>
            [DebuggerStepThrough]
            public static void Inject<T>(T existing)
            {
                _resolver.Inject(existing);
            }
    
            /// <summary>
            /// 解析对象
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="type"></param>
            /// <returns></returns>
            [DebuggerStepThrough]
            public static T Resolve<T>(Type type)
            {
                return _resolver.Resolve<T>(type);
            }
            /// <summary>
            /// 解析对象
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="type"></param>
            /// <param name="name"></param>
            /// <returns></returns>
            [DebuggerStepThrough]
            public static T Resolve<T>(Type type, string name)
            {
                return _resolver.Resolve<T>(type, name);
            }
            /// <summary>
            /// 解析对象
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <returns></returns>
            [DebuggerStepThrough]
            public static T Resolve<T>()
            {
                return _resolver.Resolve<T>();
            }
            /// <summary>
            /// 解析对象
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="name"></param>
            /// <returns></returns>
            [DebuggerStepThrough]
            public static T Resolve<T>(string name)
            {
                return _resolver.Resolve<T>(name);
            }
            /// <summary>
            /// 解析对象
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <returns></returns>
            [DebuggerStepThrough]
            public static IEnumerable<T> ResolveAll<T>()
            {
                return _resolver.ResolveAll<T>();
            }
            /// <summary>
            /// 销毁
            /// </summary>
            [DebuggerStepThrough]
            public static void Reset()
            {
                if (_resolver != null)
                {
                    _resolver.Dispose();
                }
            }
        }
    }
    

    6.配置文件

    <configuration>
      <configSections>
        <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    
        <!--声明容器-->
        <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration"/>
    
      </configSections>
    
      <unity>
        <!--定义类型别名-->
        <aliases>
          <add alias="IProduct" type="UnityTest.IProduct,UnityTest" />
          <add alias="Milk" type="UnityTest.Milk,UnityTest" />
          <add alias="Sugar" type="UnityTest.Sugar,UnityTest" />
        </aliases>
        <!--容器-->
        <container name="UnityContainer">
          <!--映射关系-->
          <register type="IProduct"  mapTo="Milk"  name="Milk"></register>
          <register type="IProduct"  mapTo="Sugar" name="Sugar"></register>
        </container>
      </unity>
    
      <connectionStrings>
        <add name="DefaultConnection" connectionString="Data Source=(LocalDb)MSSQLLocalDB;AttachDbFilename=|DataDirectory|aspnet-UnityTest-20160816022913.mdf;Initial Catalog=aspnet-UnityTest-20160816022913;Integrated Security=True" providerName="System.Data.SqlClient" />
      </connectionStrings>
      <appSettings>
        <add key="webpages:Version" value="3.0.0.0" />
        <add key="webpages:Enabled" value="false" />
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    
        <!--Unity IOC容器-->
        <add key="DependencyResolverTypeName" value="IOCContainer.UnityDependencyResolver,IOCContainer"/>
    
      </appSettings>
        <!--省略了其他配置...-->
    </configuration>
    

      

    7.具体实体类

    /// <summary>
        /// 商品
        /// </summary>
        public interface IProduct
        {
            string ClassName { get; set; }
            string ShowInfo();
        }
        /// <summary>
        /// 牛奶
        /// </summary>
        public class Milk : IProduct
        {
            public string ClassName { get; set; }
            public string ShowInfo()
            {
                return "牛奶";
            }
        }
        /// <summary>
        /// 糖
        /// </summary>
        public class Sugar : IProduct
        {
            public string ClassName { get; set; }
            public string ShowInfo()
            {
                return "糖";
            }
        }
    

    8.使用Ioc得到对象

           //初始化 指定注册器
                IoC.InitializeWith(new DependencyResolverFactory("IOCContainer.UnityDependencyResolver"));
                //初始化 使用默认注册器,配置文件中配置,IOCContainer.UnityDependencyResolver 的无参构造函数
                //IoC.InitializeWith(new DependencyResolverFactory());
    
                //得到实例
                IProduct sugar = IoC.Resolve<IProduct>("Sugar");
                string result = sugar.ShowInfo();
                Response.Write(result);
    

      来源:http://www.cnblogs.com/qqlin/archive/2012/10/18/2720830.html

  • 相关阅读:
    【linux 爱好者群】程序猿的那些聊天记录
    开发技巧记录
    tcmalloc 内存分析
    mktime很慢就自己去实现一个吧
    bash变量常用技巧
    文本处理sed常用操作
    【TED】如何掌握你的自由时间
    vim粘贴代码问题
    工作方式的反思-20170319
    【one day one linux】find 用法详解小记
  • 原文地址:https://www.cnblogs.com/xsj1989/p/5845927.html
Copyright © 2020-2023  润新知