|
| 1 | +# 1. Getting Started |
| 2 | + |
| 3 | +Version 2.0.0 :arrow_up: (Simple code examples: https://github.com/cdcd72/NetCore.AspectCore.AOP.Demo) |
| 4 | +Version 2.0.0 :arrow_down: (Simple code examples: https://github.com/fs7744/AspectCoreDemo) |
| 5 | + |
| 6 | +## Start Using AspectCore |
| 7 | + |
| 8 | +* Launch Visual Studio. From the File menu, select New > Project. Select the ASP.NET Core Web Application project template to create a new ASP.NET Core Web Application project. |
| 9 | + |
| 10 | +* Install `AspectCore.Extensions.DependencyInjection` package from Nuget: |
| 11 | + ``` |
| 12 | + PM> Install-Package AspectCore.Extensions.DependencyInjection |
| 13 | + ``` |
| 14 | +* In general cases, you can use the abstract `AbstractInterceptorAttribute` to customize your attribute class, which implements the `IInterceptor` interface. AspectCore provides default interceptor configuration based on `Attribute`. Our custom interceptor looks like this: |
| 15 | + ```csharp |
| 16 | + public class CustomInterceptorAttribute : AbstractInterceptorAttribute |
| 17 | + { |
| 18 | + public async override Task Invoke(AspectContext context, AspectDelegate next) |
| 19 | + { |
| 20 | + try |
| 21 | + { |
| 22 | + Console.WriteLine("Before service call"); |
| 23 | + await next(context); |
| 24 | + } |
| 25 | + catch (Exception) |
| 26 | + { |
| 27 | + Console.WriteLine("Service threw an exception!"); |
| 28 | + throw; |
| 29 | + } |
| 30 | + finally |
| 31 | + { |
| 32 | + Console.WriteLine("After service call"); |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + ``` |
| 37 | +* Define the `ICustomService` interface and its implementation class `CustomService`: |
| 38 | + ```csharp |
| 39 | + public interface ICustomService |
| 40 | + { |
| 41 | + [CustomInterceptor] |
| 42 | + void Call(); |
| 43 | + } |
| 44 | +
|
| 45 | + public class CustomService : ICustomService |
| 46 | + { |
| 47 | + public void Call() |
| 48 | + { |
| 49 | + Console.WriteLine("service calling..."); |
| 50 | + } |
| 51 | + } |
| 52 | + ``` |
| 53 | +* Inject `ICustomService` in `HomeController`: |
| 54 | + ```csharp |
| 55 | + public class HomeController : Controller |
| 56 | + { |
| 57 | + private readonly ICustomService _service; |
| 58 | + public HomeController(ICustomService service) |
| 59 | + { |
| 60 | + _service = service; |
| 61 | + } |
| 62 | +
|
| 63 | + public IActionResult Index() |
| 64 | + { |
| 65 | + _service.Call(); |
| 66 | + return View(); |
| 67 | + } |
| 68 | + } |
| 69 | + ``` |
| 70 | +* Register `ICustomService`, then configure the container to create proxy types in `ConfigureServices`: |
| 71 | + ```csharp |
| 72 | + public void ConfigureServices(IServiceCollection services) |
| 73 | + { |
| 74 | + services.AddTransient<ICustomService, CustomService>(); |
| 75 | + services.AddMvc(); |
| 76 | + services.ConfigureDynamicProxy(); |
| 77 | + } |
| 78 | + ``` |
| 79 | +* Finally, add `UseServiceProviderFactory(new DynamicProxyServiceProviderFactory())` to `Program`'s `CreateHostBuilder`: |
| 80 | + ```csharp |
| 81 | + public static IHostBuilder CreateHostBuilder(string[] args) => |
| 82 | + Host.CreateDefaultBuilder(args) |
| 83 | + .ConfigureWebHostDefaultsDefaults(webBuilder => |
| 84 | + { |
| 85 | + webBuilder.UseStartup<Startup>(); |
| 86 | + }) |
| 87 | + // ... |
| 88 | + .UseServiceProviderFactory(new DynamicProxyServiceProviderFactory()); |
| 89 | + ``` |
| 90 | +
|
| 91 | +--- |
| 92 | +## Interceptor Configuration |
| 93 | +
|
| 94 | +* Global interceptors. Use the `ConfigureDynamicProxy(Action<IAspectConfiguration>)` overload method, where `IAspectConfiguration` provides `Interceptors` to register global interceptors: |
| 95 | + ```csharp |
| 96 | + services.ConfigureDynamicProxy(config => |
| 97 | + { |
| 98 | + config.Interceptors.AddTyped<CustomInterceptorAttribute>(); |
| 99 | + }); |
| 100 | + ``` |
| 101 | + Global interceptor with constructor parameters. Add a parameterized constructor in `CustomInterceptorAttribute`: |
| 102 | + ```csharp |
| 103 | + public class CustomInterceptorAttribute : AbstractInterceptorAttribute |
| 104 | + { |
| 105 | + private readonly string _name; |
| 106 | + public CustomInterceptorAttribute(string name) |
| 107 | + { |
| 108 | + _name = name; |
| 109 | + } |
| 110 | + public async override Task Invoke(AspectContext context, AspectDelegate next) |
| 111 | + { |
| 112 | + try |
| 113 | + { |
| 114 | + Console.WriteLine("Before service call"); |
| 115 | + await next(context); |
| 116 | + } |
| 117 | + catch (Exception) |
| 118 | + { |
| 119 | + Console.WriteLine("Service threw an exception!"); |
| 120 | + throw; |
| 121 | + } |
| 122 | + finally |
| 123 | + { |
| 124 | + Console.WriteLine("After service call"); |
| 125 | + } |
| 126 | + } |
| 127 | + } |
| 128 | + ``` |
| 129 | + Modify global interceptor registration: |
| 130 | + ```csharp |
| 131 | + services.ConfigureDynamicProxy(config => |
| 132 | + { |
| 133 | + config.Interceptors.AddTyped<CustomInterceptorAttribute>(args: new object[] { "custom" }); |
| 134 | + }); |
| 135 | + ``` |
| 136 | + Global interceptor as a service. Add in `ConfigureServices`: |
| 137 | + ```csharp |
| 138 | + services.AddTransient<CustomInterceptorAttribute>(provider => new CustomInterceptorAttribute("custom")); |
| 139 | + ``` |
| 140 | + Modify global interceptor registration: |
| 141 | + ```csharp |
| 142 | + services.ConfigureDynamicProxy(config => |
| 143 | + { |
| 144 | + // Add registered service |
| 145 | + config.Interceptors.AddServiced<CustomInterceptorAttribute>(); |
| 146 | + }); |
| 147 | + ``` |
| 148 | + Global interceptor targeting specific `Service` or `Method`. The following code demonstrates a global interceptor acting on classes ending with `Service`: |
| 149 | + ```csharp |
| 150 | + services.ConfigureDynamicProxy(config => |
| 151 | + { |
| 152 | + config.Interceptors.AddTyped<CustomInterceptorAttribute>(method => method.Name.EndsWith("MethodName")); |
| 153 | + }); |
| 154 | + ``` |
| 155 | + Specific global interceptor using wildcards: |
| 156 | + ```csharp |
| 157 | + services.ConfigureDynamicProxy(config => |
| 158 | + { |
| 159 | + config.Interceptors.AddTyped<CustomInterceptorAttribute>(Predicates.ForService("*Service")); |
| 160 | + }); |
| 161 | + ``` |
| 162 | +
|
| 163 | +* AspectCore provides `NonAspectAttribute` to make `Service` or `Method` not proxied: |
| 164 | + ```csharp |
| 165 | + [NonAspect] |
| 166 | + public interface ICustomService |
| 167 | + { |
| 168 | + void Call(); |
| 169 | + } |
| 170 | + ``` |
| 171 | + Also supports global ignore configuration and wildcards: |
| 172 | + ```csharp |
| 173 | + services.ConfigureDynamicProxy(config => |
| 174 | + { |
| 175 | + // Services under App1 namespace won't be proxied |
| 176 | + config.NonAspectPredicates.AddNamespace("App1"); |
| 177 | +
|
| 178 | + // Services under namespaces where the last level is App1 won't be proxied |
| 179 | + config.NonAspectPredicates.AddNamespace("*.App1"); |
| 180 | +
|
| 181 | + // ICustomService interface won't be proxied |
| 182 | + config.NonAspectPredicates.AddService("ICustomService"); |
| 183 | +
|
| 184 | + // Interfaces and classes ending with Service won't be proxied |
| 185 | + config.NonAspectPredicates.AddService("*Service"); |
| 186 | +
|
| 187 | + // Methods named Query won't be proxied |
| 188 | + config.NonAspectPredicates.AddMethod("Query"); |
| 189 | +
|
| 190 | + // Methods ending with Query won't be proxied |
| 191 | + config.NonAspectPredicates.AddMethod("*Query"); |
| 192 | + }); |
| 193 | + ``` |
| 194 | +
|
| 195 | +* Dependency injection in interceptors. Supports property injection, constructor injection, and service locator pattern in interceptors. |
| 196 | +
|
| 197 | + Property injection. In interceptors, mark properties with `public get and set` permissions with the `[AspectCore.DependencyInjection.FromServiceContextAttribute]` attribute to automatically inject the property: |
| 198 | + ```csharp |
| 199 | + public class CustomInterceptorAttribute : AbstractInterceptorAttribute |
| 200 | + { |
| 201 | + // ps: Property injection only works when using config.Interceptors.AddTyped<CustomInterceptorAttribute>(); |
| 202 | + // It does not work with services.AddSingleton<CustomInterceptorAttribute>(); + services.ConfigureDynamicProxy(config => { config.Interceptors.AddServiced<CustomInterceptorAttribute>(); }); |
| 203 | + [FromServiceContext] |
| 204 | + public ILogger<CustomInterceptorAttribute> Logger { get; set; } |
| 205 | +
|
| 206 | + public override Task Invoke(AspectContext context, AspectDelegate next) |
| 207 | + { |
| 208 | + Logger.LogInformation("call interceptor"); |
| 209 | + return next(context); |
| 210 | + } |
| 211 | + } |
| 212 | + ``` |
| 213 | + Constructor injection requires the interceptor to be a `Service`. Besides global interceptors, you can still use `ServiceInterceptor` to make interceptors activated from DI: |
| 214 | +
|
| 215 | + ```csharp |
| 216 | + public class CustomInterceptorAttribute : AbstractInterceptorAttribute |
| 217 | + { |
| 218 | + private readonly ILogger<CustomInterceptor> ctorlogger; |
| 219 | +
|
| 220 | + // ps: When globally configured with config.Interceptors.AddTyped<CustomInterceptorAttribute>(), constructor injection cannot be automatically injected, needs manual handling |
| 221 | + // Only works with services.AddSingleton<CustomInterceptorAttribute>(); + services.ConfigureDynamicProxy(config => { config.Interceptors.AddServiced<CustomInterceptorAttribute>(); }); |
| 222 | + public CustomInterceptor(ILogger<CustomInterceptor> ctorlogger) |
| 223 | + { |
| 224 | + this.ctorlogger = ctorlogger; |
| 225 | + } |
| 226 | + } |
| 227 | + ``` |
| 228 | +
|
| 229 | + Service locator pattern. The interceptor context `AspectContext` can get the current scoped `ServiceProvider`: |
| 230 | + ```csharp |
| 231 | + public class CustomInterceptorAttribute : AbstractInterceptorAttribute |
| 232 | + { |
| 233 | + public override Task Invoke(AspectContext context, AspectDelegate next) |
| 234 | + { |
| 235 | + var logger = context.ServiceProvider.GetService<ILogger<CustomInterceptorAttribute>>(); |
| 236 | + logger.LogInformation("call interceptor"); |
| 237 | + return next(context); |
| 238 | + } |
| 239 | + } |
| 240 | + ``` |
| 241 | +
|
| 242 | +Version 2.0.0 :arrow_up: ps: Original text (https://www.thinkinmd.com/post/2020/03/20/use-aspectcore-to-implement-aop-mechanism/) |
| 243 | +Version 2.0.0 :arrow_down: ps: Original text (http://www.cnblogs.com/liuhaoyang/p/aspectcore-introduction-1.html) |
0 commit comments