解决在.net8 WebAPI中 使用AbstractInterceptorAttribute 实现AOP 拦截器
1.解决在.net8 WebAPI中 使用AbstractInterceptorAttribute 实现AOP 拦截器
2..net8 AOP 实现简单的Json Redis 缓存/业务分离在网上找了许多例子 但是放在.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 框架交流群)
未经作者同意,禁止转发
合集:
C#
, .net Coer AOP篇
标签:
C#
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器