1. 程式人生 > >菜渣開源一個基於 EMIT 的 AOP 庫(.NET Core)

菜渣開源一個基於 EMIT 的 AOP 庫(.NET Core)

[TOC] Nuget 庫地址:https://www.nuget.org/packages/CZGL.AOP/ Github 庫地址:https://github.com/whuanle/CZGL.AOP CZGL.AOP 是 基於 EMIT 編寫的 一個簡單輕量的AOP框架,支援非侵入式代理,支援.NET Core/ASP.NET Core,以及支援多種依賴注入框架。 # 1,快速入門 CZGL.AOP 使用比較簡單,你只需要使用 `[Interceptor]` 特性標記需要代理的型別,然後使用繼承 `ActionAttribute` 的特性標記要被代理的方法或屬性。 ### 1.1 繼承 ActionAttribute 特性 `ActionAttribute` 是用於代理方法或屬性的特性標記,不能直接使用,需要繼承後重寫方法。 示例如下: ```csharp public class LogAttribute : ActionAttribute { public override void Before(AspectContext context) { Console.WriteLine("執行前"); } public override object After(AspectContext context) { Console.WriteLine("執行後"); if (context.IsMethod) return context.MethodResult; else if (context.IsProperty) return context.PropertyValue; return null; } } ``` `Before` 會在被代理的方法執行前或被代理的屬性呼叫時生效,你可以通過 `AspectContext` 上下文,獲取、修改傳遞的引數。 After 在方法執行後或屬性呼叫時生效,你可以通過上下文獲取、修改返回值。 ### 1.2 標記代理型別 在被代理的型別中,使用 `[Interceptor]` 特性來標記,在需要代理的方法中,使用 繼承了 `ActionAttribute` 的特性來標記。 此方法是侵入式的,需要在編譯前完成。 ```csharp [Interceptor] public class Test : ITest { [Log] public virtual string A { get; set; } [Log] public virtual void MyMethod() { Console.WriteLine("執行中"); } } ``` 注意的是,一個方法或屬性只能設定一個攔截器。 ## 2,如何建立代理型別 CZGL.AOP 有多種生成代理型別的方式,下面介紹簡單的方式。 請預先建立如下程式碼: ```csharp public class LogAttribute : ActionAttribute { public override void Before(AspectContext context) { Console.WriteLine("執行前"); } public override object After(AspectContext context) { Console.WriteLine("執行後"); if (context.IsMethod) return context.MethodResult; else if (context.IsProperty) return context.PropertyValue; return null; } } public interface ITest { void MyMethod(); } [Interceptor] public class Test : ITest { [Log] public virtual string A { get; set; } public Test() { Console.WriteLine("建構函式沒問題"); } [Log] public virtual void MyMethod() { Console.WriteLine("執行中"); } } ``` #### 2.1 通過API直接建立 通過 CZGL.AOP 中的 `AopInterceptor` 類,你可以生成代理型別。 示例如下: ```csharp ITest test1 = AopInterceptor.CreateProxyOfInterface(); Test test2 = AopInterceptor.CreateProxyOfClass(); test1.MyMethod(); test2.MyMethod(); ``` `CreateProxyOfInterface` 通過介面建立代理型別;`CreateProxyOfClass` 通過類建立代理型別; 預設呼叫的是無參建構函式。 # 2,建立代理型別 ## 通過API 你可以參考原始碼解決方案 中的 ExampleConsole 專案。 如果要直接使用 `AopInterceptor.CreateProxyOfInterface` 和 `AopInterceptor.CreateProxyOfClass` 方法,通過介面或類來建立代理型別。 ```csharp ITest test1 = AopInterceptor.CreateProxyOfInterface(); Test test2 = AopInterceptor.CreateProxyOfClass(); ``` 如果要指定例項化的建構函式,可以這樣: ```csharp // 指定建構函式 test2 = AopInterceptor.CreateProxyOfClass("aaa", "bbb"); test2.MyMethod(); ``` ## 通過 Microsoft.Extensions.DependencyInjection `Microsoft.Extensions.DependencyInjection` 是 .NET Core/ASP.NET Core 預設的依賴注入容器。 如果需要支援 ASP.NET Core 中使用 AOP,你可以在 Nuget 包中安裝 `CZGL.AOP.MEDI`。 如果你在控制檯下使用 `Microsoft.Extensions.DependencyInjection`,你可以使用名為 `BuildAopProxy` 的 `IServiceCollection` 拓展方法來為容器中的型別,生成代理型別。 示例如下: ```csharp IServiceCollection _services = new ServiceCollection(); _services.AddTransient(); var serviceProvider = _services.BuildAopProxy().BuildServiceProvider(); serviceProvider.GetService(); return serviceProvider; ``` 你可以參考原始碼解決方案中的 `ExampleMEDI` 專案。 如果你要在 ASP.NET Core 中使用,你可以在 `Startup` 中,`ConfigureServices` 方法的最後一行程式碼使用 `services.BuildAopProxy();` 。 ```csharp public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.BuildAopProxy(); } ``` 還可以在 `Program` 的 `IHostBuilder` 中使用 ` .UseServiceProviderFactory(new AOPServiceProxviderFactory())` 來配置使用 CZGL.AOP。 示例: ```csharp public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseServiceProviderFactory(new AOPServiceProxviderFactory()) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }); ``` 可以參考解決方案中的 `ExampleConsole` 和 `ExampleWebMEDI` 兩個專案。 你不必擔心引入 CZGL.AOP 後,使用依賴注入會使程式變慢或者破壞容器中的原有屬性。CZGL.AOP 只會在建立容器時處理需要被代理的型別,不會影響容器中的服務,也不會干擾到依賴注入的執行。 ### 通過 Autofac 如果需要在 Autofac 中使用 AOP,則需要引用 `CZGL.AOP.Autofac` 包。 如果你在控制檯程式中使用 Autofac,則可以在 `Build()` 後面使用 `BuildAopProxy()`。 ```csharp ContainerBuilder builder = new ContainerBuilder(); builder.RegisterType().As(); var container = builder.Build().BuildAopProxy(); using (ILifetimeScope scope = container.BeginLifetimeScope()) { // 獲取例項 ITest myService = scope.Resolve(); myService.MyMethod(); } Console.ReadKey(); } ``` 要注意的是,在已經完成的元件註冊建立一個新的容器後,才能呼叫 `BuildAopProxy()` 方法, 這樣針對一個新的容器你可以考慮是否需要對容器中的元件進行代理。 如果在 ASP.NET Core 中使用 Autofac,你需要在 Program 類的 IHostBuilder 中使用: ```csharp .UseServiceProviderFactory(new AutofacServiceProviderFactory()) ``` 如果需要代理已經註冊的元件,則將其替換為: ```csharp .UseServiceProviderFactory(new CZGL.AOP.Autofac.AOPServiceProxviderFactory()) ``` 請參考 原始碼解決方案中的 `ExampleAutofac` 和 `ExampleWebAutofac` 兩個專案。 # 3,深入使用 ## 代理型別 要被代理的型別,需要使用 `[Interceptor]`來標記,例如: ```csharp [Interceptor] public class Test : ITest { } ``` 支援泛型型別。 被代理的型別必須是可被繼承的。 型別的建構函式沒有限制,你可以隨意編寫。 在使用 API 建立代理型別並且例項化時,你可以指定使用哪個建構函式。 例如: ```csharp string a="",b="",c=""; ITest test1 = AopInterceptor.CreateProxyOfInterface(a,b,c); ``` API 會根據引數的多少以及引數的型別自動尋找合適的建構函式。 ## 方法、屬性代理 為了代理方法或屬性,你需要繼承 `ActionAttribute` 特性,然後為方法或屬性標記此特性,並且將方法或屬性設定為 `virtual` 一個型別中的不同方法,可以使用不同的攔截器。 ```csharp [Log1] public virtual void MyMethod1(){} [Log2] public virtual void MyMethod2(){} ``` 對於屬性,可以在屬性上直接使用特性,或者只在 get 或 set 構造器使用。 ```csharp [Log] public virtual string A { get; set; } // 或 public virtual string A { [Log] get; set; } // 或 public virtual string A { get; [Log] set; } ``` 如果在屬性上使用特性,相當於 `[Log] get; [Log] set;`。 ## 上下文 一個簡單的方法或屬性攔截標記是這樣的: ```csharp public class LogAttribute : ActionAttribute { public override void Before(AspectContext context) { Console.WriteLine("執行前"); } public override object After(AspectContext context) { Console.WriteLine("執行後"); if (context.IsMethod) return context.MethodResult; else if (context.IsProperty) return context.PropertyValue; return null; } } ``` AspectContext 的屬性說明如下: | 欄位 | 說明 | | -------------------- | ------------------------------------------------------------ | | Type | 當前被代理型別生成的代理型別 | | ConstructorParamters | 型別被例項化時使用的建構函式的引數,如果建構函式沒有引數,則 MethodValues.Length = 0,而不是 MethodValues 為 null。 | | IsProperty | 當前攔截的是屬性 | | PropertyInfo | 當前被執行的屬性的資訊,可為 null。 | | PropertyValue | 但呼叫的是屬性時,返回 get 的結果或 set 的 value 值。 | | IsMethod | 當前攔截的是方法 | | MethodInfo | 當前方法的資訊 | | MethodValues | 方法被呼叫時傳遞的引數,如果此方法沒有引數,則 MethodValues.Length = 0,而不是 MethodValues 為 null | | MethodResult | 方法執行返回的結果(如果有) | ### 攔截方法或屬性的引數 通過上下文,你可以修改方法或屬性的引數以及攔截返回結果: ```csharp public class LogAttribute : ActionAttribute { public override void Before(AspectContext context) { // 攔截並修改方法的引數 for (int i = 0; i < context.MethodValues.Length; i++) { context.MethodValues[i] = (int)context.MethodValues[i] + 1; } Console.WriteLine("執行前"); } public override object After(AspectContext context) { Console.WriteLine("執行後"); // 攔截方法的執行結果 context.MethodResult = (int)context.MethodResult + 664; if (context.IsMethod) return context.MethodResult; else if (context.IsProperty) return context.PropertyValue; return null; } } [Interceptor] public class Test { [Log] public virtual int Sum(int a, int b) { Console.WriteLine("執行中"); return a + b; } } ``` ```csharp Test test = AopInterceptor.CreateProxyOfClass(); Console.WriteLine(test.Sum(1, 1)); ``` 方法的引數支援 `in`、`ref`、`out`;支援泛型方法泛型屬性;支援非同步方法; ## 非侵入式代理 此種方式不需要改動被代理的型別,你也可以代理程式集中的型別。 ```csharp public class LogAttribute : ActionAttribute { public override void Before(AspectContext context) { Console.WriteLine("執行前"); } public override object After(AspectContext context) { Console.WriteLine("執行後"); if (context.IsMethod) return context.MethodResult; else if (context.IsProperty) return context.PropertyValue; return null; } } ``` ```csharp public class TestNo { public virtual string A { get; set; } public virtual void MyMethod() { Console.WriteLine("執行中"); } } ``` ```csharp TestNo test3 = AopInterceptor.CreateProxyOfType(new ProxyTypeBuilder() .AddProxyMethod(typeof(LogAttribute), typeof(TestNo).GetMethod(nameof(TestNo.MyMethod))) .AddProxyMethod(typeof(LogAttribute), typeof(TestNo).GetProperty(nameof(TestNo.A)).GetSetMethod())); ``` 通過 ProxyTypeBuilder 來構建代理型別。 代理方法或屬性都是使用 `AddProxyMethod`,第一個引數是要使用的攔截器,第二個引數是要攔截的方法。 如果要攔截屬性,請分開設定屬性的 `get`、`set` 構造。 如果多個方法或屬性使用同一個攔截器,則可以這樣: ```csharp TestNo test3 = AopInterceptor.CreateProxyOfType( new ProxyTypeBuilder(new Type[] { typeof(LogAttribute) }) .AddProxyMethod("LogAttribute", typeof(TestNo).GetMethod(nameof(TestNo.MyMethod))) .AddProxyMethod("LogAttribute", typeof(TestNo).GetProperty(nameof(TestNo.A)).GetSetMethod())); ``` ```csharp TestNo test3 = AopInterceptor.CreateProxyOfType( new ProxyTypeBuilder(new Type[] { typeof(LogAttribute) }) .AddProxyMethod("LogAttribute", typeof(TestNo).GetMethod(nameof(TestNo.MyMethod))) .AddProxyMethod(typeof(LogAttribute2), typeof(TestNo).GetProperty(nameof(TestNo.A)).GetSetMethod())); ``` 在建構函式中傳遞過去所需要的攔截器,然後在攔截時使用。