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

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

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), true) as Microsoft.Practices.Unity.DependencyAttribute[]; 
                if (attrs != null && attrs.Length > 0) 
                { 
                    return true; 
                } 
            } 
            return false; 
        } 
    } 
}

测试:

[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(); 
    }

效果:

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

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

附件下载: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

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

  1. spring aop 必须的包 及里面用到的东西_Spring 原理初探——IoC、AOP

    前言 众所周知, 现在的 Spring 框架已经成为构建企业级 Java 应用事实上的标准了,众多的企业项目都构建在 Spring 项目及其子项目之上,特别是 Java Web 项目. Spring ...

  2. Spring IOC 容器源码分析 - 填充属性到 bean 原始对象

    1. 简介 本篇文章,我们来一起了解一下 Spring 是如何将配置文件中的属性值填充到 bean 对象中的.我在前面几篇文章中介绍过 Spring 创建 bean 的流程,即 Spring 先通过反 ...

  3. ioc spring 上机案例_抛开Spring去理解IOC思想 - 原来IOC容器这么简单

    很多小伙伴们看到标题可能就会想到抛开Spring就不会存在IOC思想了,其实不然在接下来的文章中就会讲述到. 很多小伙伴在理解IOC的时候通常会和Spring放到一起去学习,首先呢Spring设计的非 ...

  4. 一步一步手绘Spring IOC运行时序图一(Spring 核心容器 IOC初始化过程)

    相关内容: 架构师系列内容:架构师学习笔记(持续更新) 一步一步手绘Spring IOC运行时序图一(Spring 核心容器 IOC初始化过程) 一步一步手绘Spring IOC运行时序图二(基于XM ...

  5. 一步一步手绘Spring IOC运行时序图三(基于Annotation的IOC容器初始化)

    相关内容: 架构师系列内容:架构师学习笔记(持续更新) 一步一步手绘Spring IOC运行时序图一(Spring 核心容器 IOC初始化过程) 一步一步手绘Spring IOC运行时序图二(基于XM ...

  6. 一步一步手绘Spring IOC运行时序图二(基于XML的IOC容器初始化)

    相关内容: 架构师系列内容:架构师学习笔记(持续更新) 一步一步手绘Spring IOC运行时序图一(Spring 核心容器 IOC初始化过程) 一步一步手绘Spring IOC运行时序图二(基于XM ...

  7. Rhyme/Spring是如何简化Java开发的(POJO、DI、AOP、模板)

    Spring是如何简化Java开发的 Spring是为了解决企业及应用的复杂性而创建的,使用spring创建的pojo对象,也就是简单的java类,可以完成原来只有重量级的EJB对象才能完成的操作. ...

  8. 解决无法将类型为“System.Web.UI.WebControls.HiddenField”的对象强制转换为类型的错误...

    解决无法将类型为"System.Web.UI.WebControls.HiddenField"的对象强制转换为类型的错误 2008-01-04 16:14 本文章将解决: 1.解释 ...

  9. python 3.5.2设计页面_怎么解决win10系统搭建Python 3.5.2开发环境的处理方案

    今天小编告诉大家如何对win10系统搭建Python 3.5.2开发环境进行设置,可能很多用户都不知道怎么对win10系统搭建Python 3.5.2开发环境进行设置,但当我们遇到对win10系统搭建 ...

最新文章

  1. 数据管理、数据治理、数据管控的概念区别和范围是什么?
  2. java map 结构体_业务代码的救星——Java 对象转换框架 MapStruct 妙用
  3. 从任何兼容 TWAIN 的设备获取图象的控件Dynamic Web TWAIN
  4. CSS中的EM属性-弹性布局
  5. ajax链接php,关于php:在ajax切换后,单击链接没有任何作用?
  6. 页面事务处理 ContextUtil.SetComplete(); 没有 MTS 对象上下文
  7. 正则表达式(Java版整理)
  8. Windows核心编程_让窗口跟随系统样式变化
  9. 随机生成一注双色球号码
  10. java计算机毕业设计小型企业财务报销管理源码+lw文档+系统+数据库
  11. STM32中 利用PWM控制步进电机,ARR与PSC值的设定
  12. android编译环境-软硬件要求
  13. 算法探索_多序列合并去重
  14. YQP36预加水盘式成球机设计(论文+DWG图纸)
  15. 硬盘保护技术的原理和实践初探
  16. 约瑟夫环问题:有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。...
  17. 朗强:画面分割器投影拼接设备与原理
  18. Ubuntu设置某个端口只能固定IP访问
  19. 吾生也有涯,吾知也无涯_乌拉(12)
  20. 不是有效的win32程序_【西门子PLC编程实例】S7200 PLC子程序指令及应用实例

热门文章

  1. centos查看网关地址
  2. 面经(一)——5G和物联网的关系
  3. Java笔试——2021届秋招编程题汇总
  4. php生成vcf,[宜配屋]听图阁 - PHP实现生成vcf vcard文件功能类定义与使用方法详解【附demo源码下载】 原创...
  5. 提高你开发效率的十五个 Visual Studio 使用技巧
  6. 数学之路(2)-数据分析-R基础(5)
  7. 查看网口命令_20个常用Linux命令
  8. vs中imshow函数报错_opencv编程:8 imshow不显示图像和waitkey函数
  9. Unity3D重要知识点
  10. 机器学习实战:训练自己的YoloV5 [草稿-待完成]