歡迎各位轉載,轉載文章必須在文章頁面明顯位置給出作者和原文連線,否則保留追究法律責任的權利。
定義
先看看某度某科怎麼定義的 在軟體業,AOP為Aspect Oriented Programming的縮寫,意為:面向切面程式設計,通過預編譯方式和運行期間動態代理實現程式功能的統一維護的一種技術。AOP是OOP的延續,是軟體開發中的一個熱點,也是Spring框架中的一個重要內容,是函數語言程式設計的一種衍生範型。利用AOP可以對業務邏輯的各個部分進行隔離,從而使得業務邏輯各部分之間的耦合度降低,提高程式的可重用性,同時提高了開發的效率。
總結
public class ServiceAOP: IInterceptor { public void Intercept(IInvocation invocation) { DoSomething(); Console.WriteLine("我要收集請求參數,發給我們演算法模型同學 "{0}" 參數是 {1}... ", invocation.Method.Name, string.Join(", ", invocation.Arguments.Select(a => (a ?? "").ToString()).ToArray())); //執行真實業務方法 invocation.Proceed(); } public void DoSomething() { Console.WriteLine("AOP,我先說話,你們service稍後再發言!"); } }
第一種
builder.RegisterType<ServiceAOP>().As<IInterceptor>().InstancePerDependency();
//第一種方式
builder.RegisterType<TestServiceTwo>().As<ITestServiceTwo>().InterceptedBy(typeof(IInterceptor)) .InstancePerDependency().EnableClassInterceptors();
第二種
builder.Register(c => new ServiceAOP())
var serviceAsm = Assembly.Load(new AssemblyName("Sharper.Core")); builder.RegisterAssemblyTypes(serviceAsm) .Where(t => typeof(ITagService).IsAssignableFrom(t) && !t.GetTypeInfo().IsAbstract) .AsImplementedInterfaces() .InstancePerLifetimeScope() .EnableInterfaceInterceptors(); //注入攔截器
註冊程式集下所有繼承ITagService的介面,並注入攔截中介軟體
[Intercept(typeof(ServiceAOP))] public class TestServiceOne : ITestServiceTwo { public async Task FirstMethod() { //doSomething 業務邏輯 await Task.Run(() => { Console.WriteLine($"業務方法:TestServiceTwo.FirstMethod()執行成功..."); }); } }
這樣,在執行ITestServiceTwo 介面的業務方法之前,都會先執行aop中介軟體的方法操作
public class RequestCultureMiddleware { //定義私有隻讀的委託 RequestDelegate private readonly RequestDelegate _next; public RequestCultureMiddleware(RequestDelegate next) { _next = next; } //定義名為Invoke 或 InvokeAsync 的方法,參數為HttpContext public async Task InvokeAsync(HttpContext context) { Console.WriteLine($"api 請求進來了,action{context.Request.Path}"); // Call the next delegate/middleware in the pipeline await _next(context); } }
這個就是本文好說的內容,其實aop中介軟體的玩法有很多,不止於上面說的哪幾種,好可以,實現快取攔截,不同的業務方法 分別進行不同資料庫初始化,同學們可以探索一下新玩法,個人感覺,這個對項目的完整性和效率幫助還是挺大的。
歡迎各位轉載,轉載文章必須在文章頁面明顯位置給出作者和原文連線,否則保留追究法律責任的權利。
相關文章