写在前面
在上一篇中对AspectCore进行了初步的了解,用于拦截的属性加在了具体类的方法上。
C# 面向切面编程之AspectCore初探
这一篇验证一下把拦截属性加在接口上,这样实现该接口的类中所对应的方法都会被拦截到;另外示例中还尝试对方法的入参进行了修改,验证了通过AspectContext可以获得当前方法的所有信息。
代码实现
using AspectCore.DynamicProxy;
using AspectCore.DynamicProxy.Parameters;
class Program
{
static void Main(string[] args)
{
ProxyGeneratorBuilder proxyGeneratorBuilder = new ProxyGeneratorBuilder();
IProxyGenerator proxyGenerator = proxyGeneratorBuilder.Build();
SampleInterface sampleInterface = proxyGenerator.CreateInterfaceProxy<SampleInterface, SampleClass>();
Console.WriteLine(sampleInterface);
var ret = sampleInterface.Foo(1);
Console.WriteLine("ret:" + ret);
sampleInterface.Boo();
Console.ReadKey();
}
}
public class SampleInterceptor : AbstractInterceptorAttribute
{
public override Task Invoke(AspectContext context, AspectDelegate next)
{
try
{
Console.WriteLine("Call Interceptor Start");
if (context.ImplementationMethod.Name.Equals("Foo"))
{
if (context.Parameters.Length > 0)
{
Console.WriteLine($"Foo Parameter Value[0]:{context.Parameters[0]}");
context.Parameters[0] = 2;
}
var returnParam = context.GetReturnParameter();
if (returnParam != null)
{
Console.WriteLine($"return type: {returnParam.Type.Name}");
}
}
return context.Invoke(next);
}
catch (Exception ex)
{
throw;
}
finally
{
Console.WriteLine("Call Interceptor End");
}
}
}
public class SampleClass : SampleInterface
{
public virtual int Foo(int a)
{
Console.WriteLine("Call Foo:" + a);
return 1;
}
public virtual void Boo()
{
Console.WriteLine("Call Boo");
}
}
[SampleInterceptor]
public interface SampleInterface
{
int Foo(int a);
void Boo();
}