在网上找了很多例子 但是放在.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 框架交流群)
未经作者同意,禁止转发
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |