解决在.net8 WebAPI中 使用AbstractInterceptorAttribute 实现AOP 拦截器 ...

三尺非寒  金牌会员 | 2024-9-5 01:56:37 | 来自手机 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 894|帖子 894|积分 2682

在网上找了很多例子 但是放在.net8 就不好使了 比如 在Program 中配置 IInterceptor或者 services.ConfigureDynamicProxy ,网上说的对 但是也不全对
  1. //通过单元测试(MSTest)
  2. //创建IServiceCollection
  3. IServiceCollection services = new ServiceCollection();
复制代码
 是能调用AbstractInterceptorAttribute ,但是 用 WebAPI 就失效,断点都不进
尝试了网上大神的方法,发现 通过配置 失败
  1. //ConfigureDynamicProxy (失败)
  2. builder.Services.ConfigureDynamicProxy(config =>
  3. {
  4.     config.Interceptors.AddTyped<RedisInterceptorAttribute>();
  5.     config.Interceptors.AddServiced<RedisInterceptorAttribute>();
  6.     config.Interceptors.AddDelegate(async (content, next) =>
  7.     {
  8.         Console.WriteLine("delegate interceptor"); await content.Invoke(next);
  9.     });
  10.     config.Interceptors.AddTyped<RedisInterceptorAttribute>();
  11. });
复制代码
  1. //Autifac UseServiceProviderFactory (失败)
  2. builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
  3. builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder => {
  4.                 containerBuilder.RegisterType<RedisInterceptorAttribute>();
  5.                 containerBuilder.RegisterType<RedisDemoLogic>()
  6.                .EnableClassInterceptors()
  7.                .InterceptedBy(typeof(RedisInterceptorAttribute));
  8. });
复制代码
成功解决方案,使用Aotifac 
  1. //在Program 只需要配置这一句就行
  2. builder.Host.UseServiceProviderFactory(new DynamicProxyServiceProviderFactory());
复制代码
 实现AbstractInterceptorAttribute
  1.     /// <summary>
  2.     /// Json Redis缓存 注解
  3.     /// </summary>
  4.     public class RedisInterceptorAttribute : AbstractInterceptorAttribute, IEquatable<RedisInterceptorAttribute>
  5.     {
  6.           public override async Task Invoke(AspectContext context, AspectDelegate next){
  7.                   //进入方法前 ,判断是否有缓存
  8.                    await context.Invoke(next);
  9.                    //方法结束后添加到缓存
  10.           }
  11.     }
  12.    
复制代码
在使用时 在方法上一定要加virtual !!!
  1.      //一定要加virtual
  2.      [RedisInterceptor("school")]
  3.      public virtual async Task<List<string>> SelectAsync(Guid[] schoolId)
  4.      {
  5.          ///业务
  6.          return new();
  7.      }
复制代码
 完毕 一定要加virtual !!!
QQ群: 929412850 (Byte.Core 框架交流群)
未经作者同意,禁止转发

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

三尺非寒

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表