您的位置:首页 > 其它

.NET Interceptor with Dynamic Proxy

2015-10-29 17:32 423 查看
在方法执行的前后做一个操作,比如写日志等,但又不想侵入性太大,可以考虑使用动态代理来实现。

1.下载Castle

Install-Package Castle

2.示例代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Castle.DynamicProxy;

namespace CastleDynamicProxyDemo
{
class Program
{
static void Main(string[] args)
{
var generator = new ProxyGenerator();
var c = generator.CreateClassProxy<Calculator>(
new CalculatorInterceptor(),
new LogInterceptor());
c.Add(11, 22);
Console.ReadKey();
}
}

public interface ICalculator
{
int Add(int a, int b);
}

public class Calculator : ICalculator
{
public virtual int Add(int a, int b)
{
Console.WriteLine(a+b);
return a + b;
}
}

public abstract class Interceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
ExecuteBefore(invocation);
invocation.Proceed();
ExecuteAfter(invocation);
}
protected abstract void ExecuteAfter(IInvocation invocation);
protected abstract void ExecuteBefore(IInvocation invocation);
}

public class CalculatorInterceptor : Interceptor
{
protected override void ExecuteBefore(Castle.DynamicProxy.IInvocation invocation)
{
Console.WriteLine("CalculatorInterceptor Start");
}

protected override void ExecuteAfter(Castle.DynamicProxy.IInvocation invocation)
{
Console.WriteLine("CalculatorInterceptor End");
}
}

public class LogInterceptor : Interceptor
{
protected override void ExecuteBefore(Castle.DynamicProxy.IInvocation invocation)
{
Console.WriteLine("LogInterceptor Start");
}

protected override void ExecuteAfter(Castle.DynamicProxy.IInvocation invocation)
{
Console.WriteLine("LogInterceptor End");
}
}
}
输出结果:



3.总结

动态代理的这种用法类似ASP.NET MVC 中的HttpModule,可以结合Spring.NET,达到灵活配置,是责任链模式的一种体现。在我们自己设计的模块中,我们也可以使用这种方式达到更加灵活的架构.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息