用Unity 可以做IOC(控制反转) AOP(切面)可以做统一的异常和日志处理,非常方便,项目中是用微软企业库中的Microsoft.Practices.Unity实现

1 定义接口与实现

    //定义接口
public interface IProductService
{
string GetProduct();
} //实现接口
public class ProductService:IProductService
{
public string GetProduct()
{
int i = ;
int j = ;
//抛异常
return (j / i).ToString();
}
}

2 实现依赖反转

 public sealed class ServiceLocator : IServiceProvider
{
#region Private Fields
private readonly IUnityContainer container;
#endregion #region Private Static Fields
private static readonly ServiceLocator instance = new ServiceLocator();
#endregion #region Ctor
/// <summary>
/// Initializes a new instance of <c>ServiceLocator</c> class.
/// </summary>
private ServiceLocator()
{
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
container = new UnityContainer();
section.Configure(container);
}
#endregion #region Public Static Properties
/// <summary>
/// Gets the singleton instance of the <c>ServiceLocator</c> class.
/// </summary>
public static ServiceLocator Instance
{
get { return instance; }
}
#endregion #region Private Methods
private IEnumerable<ParameterOverride> GetParameterOverrides(object overridedArguments)
{
List<ParameterOverride> overrides = new List<ParameterOverride>();
Type argumentsType = overridedArguments.GetType();
argumentsType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.ToList()
.ForEach(property =>
{
var propertyValue = property.GetValue(overridedArguments, null);
var propertyName = property.Name;
overrides.Add(new ParameterOverride(propertyName, propertyValue));
});
return overrides;
}
#endregion #region Public Methods
/// <summary>
/// Gets the service instance with the given type.
/// </summary>
/// <typeparam name="T">The type of the service.</typeparam>
/// <returns>The service instance.</returns>
public T GetService<T>()
{
return container.Resolve<T>();
}
/// <summary>
/// Gets the service instance with the given type by using the overrided arguments.
/// </summary>
/// <typeparam name="T">The type of the service.</typeparam>
/// <param name="overridedArguments">The overrided arguments.</param>
/// <returns>The service instance.</returns>
public T GetService<T>(object overridedArguments)
{
var overrides = GetParameterOverrides(overridedArguments);
return container.Resolve<T>(overrides.ToArray());
}
/// <summary>
/// Gets the service instance with the given type by using the overrided arguments.
/// </summary>
/// <param name="serviceType">The type of the service.</param>
/// <param name="overridedArguments">The overrided arguments.</param>
/// <returns>The service instance.</returns>
public object GetService(Type serviceType, object overridedArguments)
{
var overrides = GetParameterOverrides(overridedArguments);
return container.Resolve(serviceType, overrides.ToArray());
}
#endregion #region IServiceProvider Members
/// <summary>
/// Gets the service instance with the given type.
/// </summary>
/// <param name="serviceType">The type of the service.</param>
/// <returns>The service instance.</returns>
public object GetService(Type serviceType)
{
return container.Resolve(serviceType);
} #endregion
}

3 异常拦截类

public class ExceptionLoggingBehavior: IInterceptionBehavior
{
public IEnumerable<Type> GetRequiredInterfaces()
{
return Type.EmptyTypes;
} public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
var methodReturn = getNext().Invoke(input, getNext);
if (methodReturn.Exception != null)
{
Console.WriteLine("拦截到异常 " + methodReturn.Exception.Message);
} return methodReturn;
} public bool WillExecute
{
get { return true; }
} }

4 App.config 配置

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<!--BEGIN: Unity-->
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration"/>
<container>
<extension type="Interception"/>
<!--Cache Provider-->
<register type="UnityAOP.IProductService, UnityAOP" mapTo="UnityAOP.ProductService, UnityAOP">
<interceptor type="InterfaceInterceptor"/>
<!--<interceptionBehavior type="UnityAOP.CachingBehavior, UnityAOP"/>-->
<interceptionBehavior type="UnityAOP.ExceptionLoggingBehavior, UnityAOP"/>
</register>
</container>
</unity>
<!--END: Unity-->
</configuration>

5 调用

static void Main(string[] args)
{
IProductService service = ServiceLocator.Instance.GetService<IProductService>();
try
{
service.GetProduct();
}
catch (Exception ex)
{ } Console.Read();
}

简单的例子

代码:http://files.cnblogs.com/files/zery/UnityAOP.rar

如果在使用时提示如下错误:

创建 unity 的配置节处理程序时出错: The type name or alias Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration could not be resolved. Please check your configuration file and verify this type name. (d:\我的文档\visual studio 2015\Projects\KMML.Web\KMML.Web\web.config line 16)

请在Nuget中安装 Unity.Interceptio即可解决

Unity 处理IOC AOP的更多相关文章

  1. C# 利用Unity 实现IOC+AOP

    public interface INoticy { void Noticy(string msg); } public class SMSNoticy : INoticy { public void ...

  2. Unity容器中AOP应用示例程序

    转发请注明出处:https://www.cnblogs.com/zhiyong-ITNote/p/9127001.html 实在没有找到Unity容器的AOP应用程序示例的说明,在微软官网找到了教程( ...

  3. Unity(IOC)学习笔记

    原文:Unity(IOC)学习笔记 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/m0_37591671/article/details/79432 ...

  4. spring ioc aop 原理

    spring ioc aop 原理 spring ioc aop 的原理 spring的IoC容器是spring的核心,spring AOP是spring框架的重要组成部分. 在传统的程序设计中,当调 ...

  5. Spring中三个重要概念 IOC AOP Bean

    Spring中三个重要概念 IOC AOP Bean 首先讲解一下Spring框架,以及为什么要使用Spring 框架? spring 是一个很好的容器框架, 是轻量级的IoC和AOP的容器框架,主要 ...

  6. IOC AOP 设计模式

    IOC AOP 不是什么技术而是一种设计模式  学习 IOC AOP 其实是在学习一种思想. 1.IOC IOC其实是 将对象的创建和获取提取到外部.由外部IOC容器提供需要的组件. 看下面代码: p ...

  7. 仿写一个简陋的 IOC/AOP 框架 mini-spring

    讲道理,感觉自己有点菜.Spring 源码看不懂,不想强行解释,等多积累些项目经验之后再看吧,但是 Spring 中的控制反转(IOC)和面向切面编程(AOP)思想很重要,为了更好的使用 Spring ...

  8. Spring Bean的生命周期、Spring MVC的工作流程、IOC,AOP

    1.Spring Bean的生命周期? (1)构造方法实例化bean. (2)构造方法设置对象属性. (3)是否实现aware接口,三种接口(BeanNameAware,BeanFactoryAwar ...

  9. Unity.Interception(AOP)

            在前面我们学习到的是Unity依赖注入(DI)与统一容器来松散耦合,这个设计已经对我们系统带来了很多的好处.但是我们还会想尝试和遵循单一职责,开放封闭原则.比如我们不应该在我们的Bus ...

随机推荐

  1. Visual studio 通用开发环境配置:SDL,FFMPEG为例

    引言 每一个C++库的使用都是从开发环境的配置开始的,其实每个库的配置过程都是大同小异,总结下来有下面几个步骤: 下载库文件,这里假定是已经预先编译完成的. 配置库文件的包含目录(include)和库 ...

  2. STemwin汉字显示

    硬件环境: STM32F429,电容屏800X480 5点触控RGB屏幕 ,SPI flash: 软件环境: UCOSIII,STemwin: 汉字显示方法: 1.在SPIflash中装在字库XBF_ ...

  3. Scala Reflection - Mirrors,ClassTag,TypeTag and WeakTypeTag

    反射reflection是程序对自身的检查.验证甚至代码修改功能.反射可以通过它的Reify功能来实时自动构建生成静态的Scala实例如:类(class).方法(method).表达式(express ...

  4. 智软科技医疗器械GSP监管软件通过多省市药监局检查

    提供医疗器械GSP监管软件,通过多省市药监局检查,符合2016年最新GSP监管条例的要求. 企业客户列表 温岭市万悦医疗器械有限公司 杭州市上善医疗器械有限公司 武汉明德生物科技股份有限公司 http ...

  5. List Set Map

    List Set 都是接口,都继承了Collection接口 ArrayList LinkList 直接实现了List接口 HashSet 实现了Set接口  TreeSet继承父类AbstractS ...

  6. Linux命令-文件文本操作grep

    文件文本操作 grep 在文件中查找符合正则表达式条件的文本行 cut 截取文件中的特定字段 paste 附加字段 tr 字符转换或压缩 sort 调整文本行的顺序,使其符合特定准则 uniq 找出重 ...

  7. iOS 10 开发适配系列 之 权限Crash问题

    升级 iOS 10 之后目测坑还是挺多的,记录一下吧,看看到时候会不会成为一个系列. 直入正题吧 今天用一个项目小小练下手,发现调用相机,崩了.试试看调用相册,又特么崩了.然后看到控制台输出了以下信息 ...

  8. Laravel大型项目系列教程(四)显示文章列表和用户修改文章

    小编心语:不知不觉已经第四部分了,非常感谢很多人给小编提的意见,改了很多bug,希望以后能继续帮小编找找茬~小编也不希望误导大家~这一节,主要讲的 是如何显示文章列表和让用户修改文章,小编预告一下(一 ...

  9. Augularjs-起步

    今年项目的需要,开始琢磨研究前端开发,由于之前项目已经用Angularjs了,就顺其而然的继续沿用. 在使用Angularjs之前,先要准备好工具:Nodejs.npm.git.bower.fis 下 ...

  10. 转:使用 Spring Data JPA 简化 JPA 开发

    从一个简单的 JPA 示例开始 本文主要讲述 Spring Data JPA,但是为了不至于给 JPA 和 Spring 的初学者造成较大的学习曲线,我们首先从 JPA 开始,简单介绍一个 JPA 示 ...