免责声明:我是此解决方案的制作者
Microsoft 确实不为 Net Core 提供现成的 AOP 解决方案。但是,我制作了一个可能会有所帮助的第 3 方项目。它直接与 Net Core 一起工作,并通过您的应用程序中的 ServiceCollection 注册插入。
Microsoft 提供的是一个名为 System.Runtime.DispatchProxy 的库,可用于为您的类创建代理对象。然而,这个代理本身并不是特别有用或功能丰富,并且需要大量额外的代码才能获得与 Castle Proxy(众所周知的动态代理库)相当的东西
考虑到这一点,我创建了一个库,它将 DispatchProxy 包装到可以在应用程序启动的 ServiceCollection 配置期间轻松注入的代码中。诀窍是有一种方法来创建属性和可以应用于您的方法的配对拦截器。然后在代理包装期间读取该属性并调用相关的拦截器。
这是一个示例拦截器属性
public class ConsoleLogAttribute : MethodInterceptorAttribute
{
}
这是一个示例拦截器类
public class ConsoleLogInterceptor : MethodInterceptor
{
public override void BeforeInvoke(IInterceptionContext interceptionContext)
{
Console.WriteLine($"Method executing: {interceptionContext.CurrentMethod.Name}");
}
public override void AfterInvoke(IInterceptionContext interceptionContext, object methodResult)
{
Console.WriteLine($"Method executed: {interceptionContext.CurrentMethod.Name}");
}
}
这就是它将如何应用于您的方法
[ConsoleLog]
public void TestMethod()
{
}
最后,这就是将它添加到您的 ServiceCollection 配置中的方式(假设您想要代理的类称为 [TestClass]:
public void ConfigureServices(IServiceCollection services)
{
// Configure Simple Proxy
services.EnableSimpleProxy(p => p.AddInterceptor<ConsoleLogAttribute, ConsoleLogInterceptor>());
// Configure your services using the Extension Methods
services.AddTransientWithProxy<ITestClass, TestClass>();
}
看看这个 GitHub 项目:https://github.com/f135ta/SimpleProxy