class DynamicProxy : DispatchProxy
{
public T? decorated { get; set; }//目标类
public Action
AOP使用
class AOPTest : IInterceptor
{
void IInterceptor.BeforeAction(object[] args)
{
Console.WriteLine($"AOP方法执行之前,args:{args}");
//throw new Exception("异常测试(异常,但依然不能影响程序执行)");
}
void IInterceptor.AfterAction(object[] args, object result)
{
Console.WriteLine($"AOP方法执行之后,args:{args},result:{result}");
}
}
interface ITestService
{
public int Add(int a, int b);
}
[Intercept(typeof(AOPTest))]
class TestService : ITestService
{
int ITestService.Add(int a, int b)
{
Console.WriteLine($"正在执行--》Add({a},{b})");
//throw new Exception("方法执行--》测试异常");
return a + b;
}
}
测试
IServiceCollection = new ServiceCollection();
serviceCollection.AddTransient(typeof(AOPTest));
serviceCollection.AddTransient();
//构建容器
ServiceHelper.BuildServiceProvider(serviceCollection);
//用工厂获取代理实例
var s = ProxyFactory.Create();
var sum = s.Add(1, 2);
Console.WriteLine("执行完毕=====>" + sum);