在方法执行的前后做一个操作,比如写日志等,但又不想侵入性太大,可以考虑使用动态代理来实现。
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,达到灵活配置,是责任链模式的一种体现。在我们自己设计的模块中,我们也可以使用这种方式达到更加灵活的架构.
本文介绍如何使用动态代理在方法执行前后执行特定操作,以Calculator类为例展示了具体实现过程,包括引入Castle库、定义拦截器接口、创建代理对象并调用方法,最终输出了方法调用前后日志信息,体现了动态代理在灵活配置和责任链模式中的应用。
1108





