Unity 处理IOC AOP
用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的更多相关文章
- C# 利用Unity 实现IOC+AOP
public interface INoticy { void Noticy(string msg); } public class SMSNoticy : INoticy { public void ...
- Unity容器中AOP应用示例程序
转发请注明出处:https://www.cnblogs.com/zhiyong-ITNote/p/9127001.html 实在没有找到Unity容器的AOP应用程序示例的说明,在微软官网找到了教程( ...
- Unity(IOC)学习笔记
原文:Unity(IOC)学习笔记 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/m0_37591671/article/details/79432 ...
- spring ioc aop 原理
spring ioc aop 原理 spring ioc aop 的原理 spring的IoC容器是spring的核心,spring AOP是spring框架的重要组成部分. 在传统的程序设计中,当调 ...
- Spring中三个重要概念 IOC AOP Bean
Spring中三个重要概念 IOC AOP Bean 首先讲解一下Spring框架,以及为什么要使用Spring 框架? spring 是一个很好的容器框架, 是轻量级的IoC和AOP的容器框架,主要 ...
- IOC AOP 设计模式
IOC AOP 不是什么技术而是一种设计模式 学习 IOC AOP 其实是在学习一种思想. 1.IOC IOC其实是 将对象的创建和获取提取到外部.由外部IOC容器提供需要的组件. 看下面代码: p ...
- 仿写一个简陋的 IOC/AOP 框架 mini-spring
讲道理,感觉自己有点菜.Spring 源码看不懂,不想强行解释,等多积累些项目经验之后再看吧,但是 Spring 中的控制反转(IOC)和面向切面编程(AOP)思想很重要,为了更好的使用 Spring ...
- Spring Bean的生命周期、Spring MVC的工作流程、IOC,AOP
1.Spring Bean的生命周期? (1)构造方法实例化bean. (2)构造方法设置对象属性. (3)是否实现aware接口,三种接口(BeanNameAware,BeanFactoryAwar ...
- Unity.Interception(AOP)
在前面我们学习到的是Unity依赖注入(DI)与统一容器来松散耦合,这个设计已经对我们系统带来了很多的好处.但是我们还会想尝试和遵循单一职责,开放封闭原则.比如我们不应该在我们的Bus ...
随机推荐
- VS2015 Update2中有关cordova和xamarin安装的问题
最近VS2015出了Update2,当然是第一时间进行了安装,中间过程曲折,反复安装卸载n次,也算是获得了一定的安装经验值.现在说一下经常出的问题. Update2里最吸引人的当然是跨平台开发的部分, ...
- 查看Sql Server被锁的表以及解锁
查看被锁表: select spId from master..SysProcesses where db_Name(dbID) = '数据库名称' and spId <> @@SpId ...
- Linux设置开机启动
开机启动 解决服务器重启,比如断点,导致服务没有启动的烦恼 1.整理机器上面运行的服务,编些成sh脚本,文件为:/home/rc/exec.sh #加载环境变量 source /etc/profi ...
- 再谈HashMap
HashMap是一个高效通用的数据结构,它在每一个Java程序中都随处可见.先来介绍些基础知识.你可能也知 道,HashMap使用key的hashCode()和equals()方法来将值划分到不同的桶 ...
- javascript 练习示例(一)
confirm 点确定返回true,点取消返回false prompt 点确定返回用户输入的字符串,点取消返回null 判断奇偶性 var isOdd = prompt('请输入你得的数字'); if ...
- 解决mysql卸载后无法从新安装,卡在最后一步的问题
mysql服务出现问题往往是最麻烦的,往往需要重装,而重装很多人卸不干净残留文件,更加装不上.在下就遇到这个问题.重装mysql到最后一步时卡在了最后一步的第二条上 解决办法就是卸载后删注册表+删数据 ...
- Atitit 衡量项目的规模
Atitit 衡量项目的规模 1. 预估衡量项目的规模的方法1 1.1. 方法一.Delphi 法1 1.2. 方法二. 类比法1 1.3. 方法三.功能点估计法1 1.4. 方法四.PERT估计法2 ...
- SalesForce 记录级别安全性
对象级安全性 简档 对象级安全性提供了控制 Salesforce.com 中数据的最简单方式.使用对象级安全性 您可以防止用户查看.创 建.编辑或删除特殊类型对象的任何实例 如潜在客户或业务机会.对象 ...
- iOS多线程之8.NSOPeration的其他用法
本文主要对NSOPeration的一些重点属性和方法做出介绍,以便大家可以更好的使用NSOPeration. 1.添加依赖 - (void)addDependency:(NSOperation * ...
- Java Web之网上购物系统(注册、登录、浏览商品、添加购物车)
眼看就要期末了,我的专业课也迎来了第二次的期末作业---------<网上购物系统>.虽然老师的意图是在锻炼我们后台的能力,但是想着还是不利用网上的模板,准备自己写,以来别人写的静态页看不 ...