asp.net core的AOP記錄


序曲:學習編程最好的方式就是敲代碼,沒有比這個更好的方法,哪怕你看了上百G的視頻,都不如你自己敲幾行代碼更為有效。還有要記得敲完代碼然后寫一篇隨筆來記錄一下你所學所想。

什么叫AOP?

AOP面向切面編程(Aspect Oriented Programming),是通過預編譯方式和運行期動態代理實現程序功能的統一維護的一種技術。

運用場景?

比較常見的場景是:日志記錄,錯誤捕獲、性能監控等 AOP的本質是通過代理對象來間接執行真實對象,在代理類中往往會添加裝飾一些額外的業務代碼。

 

下面通過代碼來說明一下,本文舉例比較簡單的案例來說明,若有錯誤,多謝指點。

建立一個asp.net core的控制台程序來演示

利用Nuget引入相關的包文件

如圖所示:

第一個攔截器的引用包 AspectCore.Extensions.DependencyInjection

第二個是依賴注入的包 Microsoft.Extensions.DependencyInjection

 

 

創建一個接口:

using System;
using System.Collections.Generic;
using System.Text;

namespace AOP_Demo
{
    public interface IMysql
    {
        void Select(int i);
    }
}

 

創建一個實現類

using System.Collections.Generic;
using System.Text;

namespace AOP_Demo
{
    class Mysql : IMysql
    {
        [MyLogInterceptor]
        public void Select(int i)
        {
            Console.WriteLine("查詢的結果是:"+i);
        }
    }
}

 

創建一個日志攔截器

using AspectCore.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks; 

namespace AOP_Demo
{
    public class MyLogInterceptorAttribute : AbstractInterceptorAttribute
    {
        public override Task Invoke(AspectContext context, AspectDelegate next)
        {
            Console.WriteLine("方法執行前的日志");
            var task = next(context);
            Console.WriteLine("方法執行后的日志");
            return task;
        }
    }
}

 

 

然后在程序入口處編寫相關代碼

using Microsoft.Extensions.DependencyInjection;
using System;
using AspectCore.Extensions.DependencyInjection;
using AspectCore.Configuration;

namespace AOP_Demo
{ 
    class Program
    {
        static void Main(string[] args)
        {
            ServiceCollection serviceDescriptors = new ServiceCollection();
            //配置動態代理
            serviceDescriptors.ConfigureDynamicProxy(config => {
                config.Interceptors.AddTyped<MyLogInterceptorAttribute>(); 
            });
            //注冊服務
            serviceDescriptors.AddTransient<IMysql, Mysql>();
            //提供者
            IServiceProvider serviceProvider = serviceDescriptors.BuildDynamicProxyServiceProvider();
            //獲得服務
            var Provider= serviceProvider.GetService<IMysql>();
            //調用方法
            Provider.Select(1);
            Console.ReadKey();
        }
    }

}

 

上面代碼中,我們需要把攔截器通過動態代理的方式注入到IOC容器中。

 

所思:面向切面就是在原來的服務上添加一點新的功能,而且這個添加的功能還不能對原來的代碼進行大改特改,盡可能的降低新功能和原來功能的耦合性,我覺得可以很好的運用在日志,異常處理等方面。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM