autofac实现aop

1.安装Autofac.Extras.DynamicProxy

2.aop切面类

 1  public class CustomAutofacAop: IInterceptor
 2     {
 3         private ILogger _logger;
 4         public CustomAutofacAop()
 5         {
 6             _logger = AppDependencyResolver.Current.GetService>();
 7 
 8         }
 9         public void Intercept(IInvocation invocation)
10         {
11             _logger.LogInformation($"invocation.Methond={invocation.Method}");
12             _logger.LogInformation($"invocation.Arguments={string.Join(",", invocation.Arguments)}");
13 
14             invocation.Proceed(); //继续执行
15 
16             _logger.LogInformation($"方法{invocation.Method}执行完成了");
17         }
18     }

3.实现类绑定aop的逻辑

 1 [Intercept(typeof(CustomAutofacAop))]
 2     public class TestAopService : ITestAopService
 3     {
 4         private ILogger _logger;
 5         public TestAopService(ILogger logger)
 6         {
 7             _logger = logger;
 8         }
 9 
10         public void Show(int id, string name)
11         {
12 
13             _logger.LogInformation($"This is {id} _ {name}");
14         }
15     }

4.注册aop实现类并且配置启用

1 //注册aop切面
2             builder.Register(c => new CustomAutofacAop());
3             //EnableInterfaceInterceptors:在该类型接口上启用aop 
4             builder.RegisterType().As().EnableInterfaceInterceptors();

 

 

 

 

你可能感兴趣的:(autofac实现aop)