天天看点

利用Attribute简化Unity框架IOC注入

     当然Unity框架中为我们提供了RegisterInstance,RegisterType方法我们可以在代码中注册到容器,比如NLayerApp中就在<code>IoCFactory中注册一大堆抽象-具体关联。但是在我们的实际实践中一般会选择另一种方式xml配置配置,因为这样我们会得到更大的灵活性,需求变化只要抽象接口不变,我们也只需要在xml配置文件中修改一行配置加入我们的具体实现,加入我们的程序集,就可以适应需求变化,这更满足oo设计“开闭原则”。</code>

<code>   在这里个人实践利用抽象(接口)定义Attribute制定具体ConfigFile(配置文件),Container(容器),Name(名称)解决IOC植入,减少我们多次去读取配置文件。Unity为我们提供了在Web.config,App.config中配置注入信息,或者注册外部配置,但是很多时候我们更希望,在我们的 不同模块下,应用不同的IOC配置信息,这些可以减少维护的关联少些,清晰,同时文件夹的出现便于我们的配置信息的管理。</code>

<code>Attribute实现:</code>

UnityInjectionAttributeView Code   

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false, Inherited = true)]   

   public class UnityInjectionAttribute : Attribute   

   {   

       public UnityInjectionAttribute(string Container)   

       {   

           this.Container = Container;              

       }   

       public string Container   

           get;   

           set;   

       public string ConfigFile   

       public string Name   

       public Microsoft.Practices.Unity.Configuration.UnityConfigurationSection GetUnityConfigurationSection()   

           if (!string.IsNullOrEmpty(this.ConfigFile))   

           {   

               var fileMap = new System.Configuration.ExeConfigurationFileMap { ExeConfigFilename = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, this.ConfigFile) };   

               System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None);   

               return configuration == null ? null : configuration.GetSection(Microsoft.Practices.Unity.Configuration.UnityConfigurationSection.SectionName) as Microsoft.Practices.Unity.Configuration.UnityConfigurationSection;   

           }   

           return System.Configuration.ConfigurationManager.GetSection(Microsoft.Practices.Unity.Configuration.UnityConfigurationSection.SectionName) as Microsoft.Practices.Unity.Configuration.UnityConfigurationSection;   

   }   

复制代码 

在这里我们GetUnityConfigurationSection根据ConfigFile获取UnityConfigurationSection ,ConfigFile为空则当前应用配置文件,不空则为路径。在这里我们为了性能,减少过多的IOC操作,读取配置文件,我们可以更具具体需要加入对配置文件UnityConfigurationSection的缓存(ConfigFile作为key,UnityConfigurationSection为value )。

   同时提供操作辅助方法:ELUnityUtility

View Code   

public static class ELUnityUtility   

       public static T Resolve&lt;T&gt;() where T : class   

           return Resolve(typeof(T)) as T;   

       public static object Resolve(this Type type)   

           var attrs = type.GetCustomAttributes(typeof(Utils.UnityInjectionAttribute), true) as Utils.UnityInjectionAttribute[];   

           if (attrs != null &amp;&amp; attrs.Length &gt; 0)   

               var attr = attrs[0];   

               var unitySection = attr.GetUnityConfigurationSection();   

               if (unitySection != null)   

               {   

                   var container = new Microsoft.Practices.Unity.UnityContainer().LoadConfiguration(unitySection, string.IsNullOrEmpty(attr.Container) ? unitySection.Containers.Default.Name : attr.Container);   

                   var obj = string.IsNullOrEmpty(attr.Name) ? container.Resolve(type) : container.Resolve(type, attr.Name);   

                   if (obj != null)   

                   {   

                       var piabAtttr = obj.GetType().GetCustomAttributes(typeof(ELPolicyinjectionAttribute), false) as ELPolicyinjectionAttribute[];   

                       if (piabAtttr.Length &gt; 0)   

                       {   

                           obj = Microsoft.Practices.EnterpriseLibrary.PolicyInjection.PolicyInjection.Wrap(type, obj);   

                       }   

                       return obj;   

                   }   

               }   

           return null;   

       public static IEnumerable&lt;T&gt; ResolveAll&lt;T&gt;() where T : class   

           return ResolveAll(typeof(T)) as IEnumerable&lt;T&gt;;   

       public static object ResolveAll(this Type type)   

                   return container.ResolveAll(type);   

   }  

这里我们就可以很简便的获取IOC翻转。注:这里还有根据具体实现是否具体ELPolicyinjectionAttribute来决定是否进行PIAB的AOP操作,当然我们也可以在Unity配置文件中引入节点扩展

Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, 

                    Microsoft.Practices.Unity.Interception.Configuration

(PIAB利用的是透明代理速度较慢所以一般很少使用,当然你也可以实现具体的PIAB AOP方式比如注入MSIL,但我们已经有了很多注入MSIL的AOP框架了,我不准备去造轮子),ELPolicyinjectionAttribute:

[AttributeUsage(AttributeTargets.Class)]   

   public class ELPolicyinjectionAttribute : Attribute   

这样:我们的客户端 就可以很简单的使用了:

class Program   

       static void Main(string[] args)   

           ELUnityUtility.Resolve&lt;IClass2&gt;().Show();   

           (typeof(IClass2).Resolve() as IClass2).Show();   

           Console.Read();   

   public interface IClass1   

       void Show();   

   [Green.Utils.ELPolicyinjection]   

   public class Class1 : IClass1   

       #region IClass1 成员   

       [TestCallHandler]   

       public void Show()   

           Console.WriteLine(this.GetType());   

       #endregion   

   [Green.Utils.UnityInjection("First", Name = "class2", ConfigFile = "App1.config")]   

   public interface IClass2   

    public class Class2 : ConsoleApplication1.IClass2   

       [Microsoft.Practices.Unity.Dependency("class1")]   

       public IClass1 Class1   

            public void Show()   

           Class1.Show();   

   }     

App1.Config配置:

&lt;?xml version="1.0" encoding="utf-8" ?&gt;   

&lt;configuration&gt;   

  &lt;configSections&gt;   

    &lt;section name="unity"   

             type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,   

             Microsoft.Practices.Unity.Configuration"/&gt;   

  &lt;/configSections&gt;   

  &lt;unity xmlns="http://schemas.microsoft.com/practices/2010/unity%22&gt;   

    &lt;container name="First"&gt;   

      &lt;register type="ConsoleApplication1.IClass1,ConsoleApplication1" mapTo="ConsoleApplication1.Class1,ConsoleApplication1" name="class1" /&gt;   

      &lt;register type="ConsoleApplication1.IClass2,ConsoleApplication1" mapTo="ConsoleApplication1.Class2,ConsoleApplication1" name="class2"  /&gt;   

    &lt;/container&gt;   

  &lt;/unity&gt;   

&lt;/configuration&gt;  

下边是一个完整的带PIAB的例子:

using System;   

using System.Collections.Generic;   

using System.Linq;   

using System.Text;   

using Green.Utils;   

using Microsoft.Practices.Unity.InterceptionExtension;   

using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;   

namespace ConsoleApplication1   

{   

    class Program   

    {   

        static void Main(string[] args)   

        {   

            ELUnityUtility.Resolve&lt;IClass2&gt;().Show();   

            (typeof(IClass2).Resolve() as IClass2).Show();   

            Console.Read();   

        }   

    }   

    public interface IClass1   

        void Show();   

    [Green.Utils.ELPolicyinjection]   

    public class Class1 : IClass1   

        #region IClass1 成员   

        [TestCallHandler]   

        public void Show()   

            Console.WriteLine(this.GetType());   

        #endregion   

    [Green.Utils.UnityInjection("First", Name = "class2", ConfigFile = "App1.config")]   

    public interface IClass2   

        [Microsoft.Practices.Unity.Dependency("class1")]   

        public IClass1 Class1   

            get;   

            set;   

            Class1.Show();   

    [Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationElementType(typeof(CustomCallHandlerData))]   

    public class TestCallHandler : ICallHandler   

        #region ICallHandler 成员   

        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)   

            if (input == null) throw new ArgumentNullException("input");   

            if (getNext == null) throw new ArgumentNullException("getNext");   

            Console.WriteLine("begin....");   

            var result = getNext()(input, getNext);   

            Console.WriteLine("end....");   

            return result;   

        public int Order   

    [AttributeUsage(AttributeTargets.Method)]   

    public class TestCallHandlerAttribute : HandlerAttribute   

        public override ICallHandler CreateHandler(Microsoft.Practices.Unity.IUnityContainer container)   

            return new TestCallHandler();   

}  

 本文转自 破狼 51CTO博客,原文链接:http://blog.51cto.com/whitewolfblog/835199,如需转载请自行联系原作者