AspectCore动态代理中的拦截器详解(一)
前言
在上一篇文章使用AspectCore動態代理中,簡單說明了AspectCore.DynamicProxy的使用方式,由于介紹的比較淺顯,也有不少同學留言詢問攔截器的配置,那么在這篇文章中,我們來詳細看一下AspectCore中的攔截器使用。
兩種配置方式
在AspectCore中,提供攔截器的特性配置和全局配置兩種使用方式,并且分別提供AbstractInterceptor(可用于全局攔截器配置)和AbstractInterceptorAttribute(可同時用于全局配置和特性配置)兩個攔截器基類。下面來分別演示兩個攔截器配置方式的使用:
特性攔截器。我們繼承AbstractInterceptorAttribute來實現一個自己的特性攔截器
? ?public override Task Invoke(AspectContext context, AspectDelegate next) ? ? { ? ? ?
? ? ?? return context.Invoke(next);}}
那么此時CustomInterceptorAttribute可以標記在需要攔截的接口,類或者方法上來開啟攔截。
全局攔截器配置。我們繼承AbstractInterceptor來實現一個自己的特性攔截器(除不能作為Attribute標記在口,類或者方法上之外,AbstractInterceptor和AbstractInterceptorAttribute并無任何區別)
? ? public override Task Invoke(AspectContext context, AspectDelegate next){ ? ?
? ? ? ? return context.Invoke(next);}}
現在我們已經定義了我們自己的攔截器,我使用Microsoft.Extensions.DependencyInjection的集成方式來演示全局攔截器的配置(需安裝AspectCore.Extensions.DependencyInjection包):
IServiceCollection services = new ServiceCollection(); services.AddDynamicProxy(config => {config.Interceptors.AddTyped<CustomInterceptor>(); }); IServiceProvider serviceProvider = services.BuildAspectCoreServiceProvider();CustomInterceptor便可以攔截由serviceProvider創建的任何服務的方法。
三種攔截器類型
在AspectCore中,提供了TypedInterceptor,ServiceInterceptor,DelegateInterceptor三種攔截器的激活類型。
TypedInterceptor
標記在接口,類或者方法上的特性攔截器或者使用上面config.Interceptors.AddTyped<CustomInterceptor>();配置的全局攔截器,這類攔截器對于每個方法具體唯一的實例。ServiceInterceptor
注冊到DI并從DI激活使用的攔截器。這類攔截器的生命周期同注冊到DI時的生命周期一致。如下面我們注冊一個瞬態的ServiceInterceptor:
我們可以使用ServiceInterceptor特性激活注冊到DI中的攔截器:
[ServiceInterceptor(typeof(CustomInterceptor))]public interface IService{ ? ?void Foo(); }或者使用全局配置:
IServiceCollection services = new ServiceCollection();services.AddTransient<CustomInterceptor>();services.AddDynamicProxy(config =>{config.Interceptors.AddServiced<CustomInterceptor>();});IServiceProvider serviceProvider = services.BuildAspectCoreServiceProvider();DelegateInterceptor
在使用全局的攔截器配置時,我們也可以不定義具體的攔截器類,而直接使用簽名為Func<AspectDelegate, AspectDelegate>或Func<AspectContext, AspectDelegate, Task>的委托來執行攔截,如下面:
? ? ? ?await content.Invoke(next);}); }); IServiceProvider serviceProvider = services.BuildAspectCoreServiceProvider();
使用通配符或者委托配置攔截器
在AspectCore中配置全局攔截器時,可以使用通配符或者委托來限定攔截器的作用范圍。
內置提供了Predicates.ForMethod,Predicates.ForService,Predicates.ForNameSpace三個通配符函數:
有問題反饋
如果您有任何問題,請提交?Issue?給我們。
Github :?https://github.com/dotnetcore/AspectCore-Framework
AspectCore QQ群: 306531723
相關文章
Asp.Net Core輕量級Aop解決方案:AspectCore
AspectCore.Extension.Reflection : .NET Core反射擴展庫
AspectCore中的IoC容器和依賴注入
使用AspectCore動態代理
原文:https://www.cnblogs.com/liuhaoyang/p/interceptor-in-aspectcore-part-1.html
.NET社區新聞,深度好文,歡迎訪問公眾號文章匯總 http://www.csharpkit.com
總結
以上是生活随笔為你收集整理的AspectCore动态代理中的拦截器详解(一)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C# 这些年来受欢迎的特性
- 下一篇: Actor-ES框架:Ray