解决在.net8 WebAPI中 使用AbstractInterceptorAttribute 实现AOP 拦截器
  x1oBGI8hwH9Y 12天前 36 0

在网上找了许多例子 但是放在.net8 就不好使了 比如 在Program 中配置 IInterceptor或者 services.ConfigureDynamicProxy ,网上说的对 但是也不全对

//通过单元测试(MSTest)
//创建IServiceCollection 
IServiceCollection services = new ServiceCollection();

 是能调用AbstractInterceptorAttribute ,但是 用 WebAPI 就失效,断点都不进

尝试了网上大神的方法,发现 通过配置 失败

//ConfigureDynamicProxy (失败)
builder.Services.ConfigureDynamicProxy(config =>
{
    config.Interceptors.AddTyped<RedisInterceptorAttribute>();
    config.Interceptors.AddServiced<RedisInterceptorAttribute>();
    config.Interceptors.AddDelegate(async (content, next) =>
    {
        Console.WriteLine("delegate interceptor"); await content.Invoke(next);
    });
    config.Interceptors.AddTyped<RedisInterceptorAttribute>();
});
//Autifac UseServiceProviderFactory (失败)
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(containerBuilder => { 
                containerBuilder.RegisterType<RedisInterceptorAttribute>();
                containerBuilder.RegisterType<RedisDemoLogic>()
               .EnableClassInterceptors()
               .InterceptedBy(typeof(RedisInterceptorAttribute));

});

成功解决方案,使用Aotifac 

//在Program 只需要配置这一句就行
builder.Host.UseServiceProviderFactory(new DynamicProxyServiceProviderFactory());

 实现AbstractInterceptorAttribute

    /// <summary>
    /// Json Redis缓存 注解
    /// </summary>
    public class RedisInterceptorAttribute : AbstractInterceptorAttribute, IEquatable<RedisInterceptorAttribute>
    { 
          public override async Task Invoke(AspectContext context, AspectDelegate next){
                  //进入方法前 ,判断是否有缓存
                   await context.Invoke(next);
                   //方法结束后添加到缓存
          }
    }
    

在使用时 在方法上一定要加virtual !!!

     //一定要加virtual
     [RedisInterceptor("school")]
     public virtual async Task<List<string>> SelectAsync(Guid[] schoolId)
     {
         ///业务
         return new();
     }

 完毕 一定要加virtual !!!

QQ群: 929412850 (Byte.Core 框架交流群)
未经作者同意,禁止转发

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 12天前 0

暂无评论

推荐阅读
x1oBGI8hwH9Y