最新免费下载ppt模板网站,网站导航做多大,qq是根据哪款软件开发的,网站建设公司如何规避风险写在前面 AspectCore 是Lemon名下的一个国产Aop框架#xff0c;提供了一个全新的轻量级和模块化的Aop解决方案。面向切面也可以叫做代码拦截#xff0c;分为静态和动态两种模式#xff0c;AspectCore 可以实现动态代理#xff0c;支持程序运行时在内存中“临时”生成 AOP 动…写在前面 AspectCore 是Lemon名下的一个国产Aop框架提供了一个全新的轻量级和模块化的Aop解决方案。面向切面也可以叫做代码拦截分为静态和动态两种模式AspectCore 可以实现动态代理支持程序运行时在内存中“临时”生成 AOP 动态代理类。
老规矩从 Nuget 安装 AspectCore.Extensions.DependencyInjection 包。 代码实现
using AspectCore.DynamicProxy;public class Program
{public static void Main(string[] args){Console.WriteLine(Start...);ProxyGeneratorBuilder proxyGeneratorBuilder new ProxyGeneratorBuilder();using (IProxyGenerator proxyGenerator proxyGeneratorBuilder.Build()){Person p proxyGenerator.CreateClassProxyPerson();Console.WriteLine(p.GetType().BaseType);p.Say(${Environment.NewLine} Hello World!);}Console.WriteLine(End);Console.ReadLine();}
}public class CustomInterceptor : AbstractInterceptorAttribute
{public async override Task Invoke(AspectContext context, AspectDelegate next){try{Console.WriteLine(Before service call);await next(context);}catch (Exception){Console.WriteLine(Service threw an exception!);throw;}finally{Console.WriteLine(After service call);}}
}public class Person
{[CustomInterceptor]public virtual void Say(string msg){Console.WriteLine(service calling... msg);}
}调用示例 如图代理类将Say方法包裹了起来。
如果修改一下CustomInterceptor 的Invoke方法可以直接根据条件控制代码的分支跳转。
public class CustomInterceptor : AbstractInterceptorAttribute
{public async override Task Invoke(AspectContext context, AspectDelegate next){try{Console.WriteLine(Before service call);if (false)await next(context);elseawait Task.Delay(1000);}catch (Exception){Console.WriteLine(Service threw an exception!);throw;}finally{Console.WriteLine(After service call);}}
} 运行代码 Person中的Say方法本体就被跳过了