AOP之PostSharp7-解决IOC 不能直接new问题,简化IOC开发和IOC对象LazyLoad

简介:

    经过几节的postsharp基础和每节的一个应用实例,已经基本PostSharp应用的能力,PostSharp主要是简化我们的开发,让编译器时候给我注入重复疲劳代码。  

   在今天我们的demo是,关于ioc(控制反转)的问题,ioc框架我们都会从ioc容器中取得我们的ioc对象注入,所以我们不能直接new对象得到我们的实例,必须Resolve。我一直都是很懒得人,既然有了PostSharp就的好好利用起来。大部份ioc逻辑是从以前的一篇利用Attribute简化Unity框架IOC注入转过来的,注入支持自定义配置文件,我个人不喜欢把配置信息全部写在一个web.config/app.config中,也不喜欢el的写在一个外部配置文件中,我个人倾向于每个模块在一个不能的配置文件,并在模块中在区分container容易,所以特别写了每个单独配置文件的延时加载,缓存。代码也不多,先上菜品:

ExpandedBlockStart.gif
复制代码
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using Microsoft.Practices.Unity; 
using Microsoft.Practices.Unity.Configuration; 
using Microsoft.Practices.Unity.InterceptionExtension; 

namespace PostSharpDemo 

    [Serializable] 
     public  class IocUnityResolverAttribute : PostSharp.Aspects.LocationInterceptionAspect 
    { 
         private Dictionary< string, Microsoft.Practices.Unity.Configuration.UnityConfigurationSection> sectionCache =  new Dictionary< string, Microsoft.Practices.Unity.Configuration.UnityConfigurationSection>(); 
         private  static  object lockObj =  new  object(); 
         public IocUnityResolverAttribute( string Container) 
        { 
             this.Container = Container; 
        } 

         public  string Container 
        { 
             get
             set
        } 

         public  string ConfigFile 
        { 
             get
             set
        } 

         public  string Name 
        { 
             get
             set
        } 

         public Microsoft.Practices.Unity.Configuration.UnityConfigurationSection GetUnityConfigurationSection() 
        { 
             if (! string.IsNullOrEmpty( this.ConfigFile)) 
            { 
                Microsoft.Practices.Unity.Configuration.UnityConfigurationSection section =  null
                 if (!sectionCache.ContainsKey( this.ConfigFile)) 
                { 
                     lock (lockObj) 
                    { 
                         if (!sectionCache.ContainsKey( 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); 
                             if (configuration ==  null
                            { 
                                 throw  new Exception( string.Format( " Unity配置{0}不正确; "this.ConfigFile)); 
                            } 
                            section = configuration.GetSection(Microsoft.Practices.Unity.Configuration.UnityConfigurationSection.SectionName)  as Microsoft.Practices.Unity.Configuration.UnityConfigurationSection; 
                            sectionCache.Add( this.ConfigFile, section); 
                        } 
                    } 
                } 
                 return sectionCache[ this.ConfigFile]; 
            } 

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

         public  override  void OnGetValue(PostSharp.Aspects.LocationInterceptionArgs args) 
        { 
             var current = args.GetCurrentValue(); 
             if (current ==  null
            { 
                 var unitySection =  this.GetUnityConfigurationSection(); 
                 if (unitySection !=  null
                { 
                     var container =  new Microsoft.Practices.Unity.UnityContainer().LoadConfiguration(unitySection,  string.IsNullOrEmpty(Container) ? unitySection.Containers.Default.Name : Container); 
                     var obj =  string.IsNullOrEmpty(Name) ? container.Resolve(args.Location.LocationType) : container.Resolve(args.Location.LocationType, Name); 
                     if (obj !=  null
                    { 
                         // var piabAtttr = obj.GetType().GetCustomAttributes(typeof(ELPolicyinjectionAttribute), false) as ELPolicyinjectionAttribute[]; 
                        
// if (piabAtttr.Length > 0) 
                        
//
                        
//     obj = Microsoft.Practices.EnterpriseLibrary.PolicyInjection.PolicyInjection.Wrap(type, obj); 
                        
//
                        args.Value = obj; 
                        args.ProceedSetValue(); 
                    } 
                } 
            } 
            args.ProceedGetValue(); 
        } 

         public  override  bool CompileTimeValidate(PostSharp.Reflection.LocationInfo locationInfo) 
        { 
             var p = locationInfo.PropertyInfo;           
             if (p !=  null
            {               
                 var attrs = p.GetCustomAttributes( typeof(Microsoft.Practices.Unity.DependencyAttribute),  trueas Microsoft.Practices.Unity.DependencyAttribute[]; 
                 if (attrs !=  null && attrs.Length >  0
                { 
                     return  true
                } 
            } 
             return  false
        } 
    } 
}
复制代码
测试:
ExpandedBlockStart.gif
复制代码
[IocUnityResolver( " IocUnityResolver ", ConfigFile =  " App1.config ")] 
    class Program 
   { 
       [Microsoft.Practices.Unity.Dependency()]        
        public  static IIocUnityResolverAttributeTest IocUnityResolverAttributeTest 
       { 
            get
            private  set

       } 
        public  static IIocUnityResolverAttributeTest IocUnityResolverAttributeTest2 
       { 
            get
            private  set

       } 

        static  void Main( string[] args) 
       { 

Program.IocUnityResolverAttributeTest.Test( " test ioc unity! "); 

        Console.Read(); 
    }
复制代码

效果:

image

另外多加一句在AOP之PostSharp初见-OnExceptionAspect这节我们系列开篇我们看了Postsharp的多播(),所以我们可以很轻松的应用于我们的程序集,类上加Attribute实现,但是这里必须要区分Location的的注入决策,所以这里重写的基类方法的CompileTimeValidate,在有EL Unity 中Microsoft.Practices.Unity.DependencyAttribute标签的location我们才会去植入。有了这些我们就很轻松的在各个类,程序集,命名空间引用。

看看我们上边的实例反编译效果,IocUnityResolverAttributeTest带有Microsoft.Practices.Unity.DependencyAttribute标签所以会植入,而IocUnityResolverAttributeTest2没有标签所以不会植入;

image

image 

附件下载:demo

AOP之PostSharp初见-OnExceptionAspect AOP之PostSharp2-OnMethodBoundaryAspect AOP之PostSharp3-MethodInterceptionAspect AOP之PostSharp4-实现类INotifyPropertyChanged植入 AOP之PostSharp5-LocationInterceptionAspect AOP之PostSharp6-EventInterceptionAspect AOP之PostSharp7-解决IOC 不能直接new问题,简化IOC开发和IOC对象LazyLoad http://www.cnblogs.com/whitewolf/category/312638.html

 


作者:破  狼 
出处:http://www.cnblogs.com/whitewolf/ 
本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。该文章也同时发布在我的独立博客中-个人独立博客博客园--破狼51CTO--破狼。http://www.cnblogs.com/whitewolf/archive/2011/12/18/PostSharp7.html


相关文章
|
6月前
|
XML Java 数据格式
Spring框架入门以及 ioc的三种注入方式
Spring框架入门以及 ioc的三种注入方式
346 0
|
API
.net core工具组件系列之Autofac—— 第二篇:Autofac的3种依赖注入方式(构造函数注入、属性注入和方法注入),以及在过滤器里面实现依赖注入
本篇文章接前一篇,建议可以先看前篇文章,再看本文,会有更好的效果。前一篇跳转链接:https://www.cnblogs.com/weskynet/p/15046999.html
411 0
.net core工具组件系列之Autofac—— 第二篇:Autofac的3种依赖注入方式(构造函数注入、属性注入和方法注入),以及在过滤器里面实现依赖注入
|
XML 设计模式 存储
Java Spring IOC容器与依赖注入DI实现原理
本文主要讲解Spring IOC机制和实现过程,依赖注入DI和面向切面编程AOP是Spring框架的核心概念,几乎后续使用到Spring Boot框架的地方都有这两个概念的影子。也是Java面试的考察点,我们会结合实际的例子演示说明 。
808 1
|
4月前
|
存储 前端开发 安全
Spring框架: 解释一下Spring框架的核心概念。
Spring框架: 解释一下Spring框架的核心概念。
40 1
|
5月前
|
XML Java 数据格式
spring框架入门介绍以及IOC的三种注入方式
spring框架入门介绍以及IOC的三种注入方式
191 0
|
10月前
|
XML 缓存 Java
Spring IOC源码:实例化前的准备工作
Spring IOC源码:实例化前的准备工作
42 0
Spring IOC源码:实例化前的准备工作
|
XML 存储 Java
springIoc简述
IoC(控制反转:Inverse of Control),又称作依赖注入,是一种重要的面向对象编程的法则来削减计算机程序的耦合问题,也是轻量级的Spring框架的核心。
|
缓存 Oracle 安全
对控制反转理解不深?带你手写一个基于注解的IOC容器 加深对spring底层代码的理解
对控制反转理解不深?带你手写一个基于注解的IOC容器 加深对spring底层代码的理解
对控制反转理解不深?带你手写一个基于注解的IOC容器 加深对spring底层代码的理解
|
Android开发
【IOC 控制反转】IOC 简介 ( 依赖注入的两种实现方式 | 编译期注入 | 运行期注入 )
【IOC 控制反转】IOC 简介 ( 依赖注入的两种实现方式 | 编译期注入 | 运行期注入 )
141 0
|
Java Spring
Spring原理学习系列之五:IOC原理之Bean加载
其实很多同学都想通过阅读框架的源码以汲取框架设计思想以及编程营养,Spring框架其实就是个很好的框架源码学习对象。我们都知道Bean是Spring框架的最小操作单元,Spring框架通过对于Bean的统一管理实现其IOC以及AOP等核心的框架功能,那么Spring框架是如何把Bean加载到环境中来进行管理的呢?本文将围绕这个话题进行详细的阐述,并配合Spring框架的源码解析。
Spring原理学习系列之五:IOC原理之Bean加载

热门文章

最新文章