net core 3.1使用autofac及Castle实现Aop切面编程

构建基本项目及引入需要的包文件

autofac在net core 3.1的使用上与2.2有不同,所以在这里记录一下。

先创建一个简单的demo项目,控制台程序及api或者mvc模式都可以。

依次引入依赖包:

Autofac:提供容器控制Autofac.Extensions.DependencyInjection:对autofac依赖注入进行扩展Autofac.Extras.DynamicProxy:对autofac动态代理进行扩展Castle.Core:使用动态代理的实现

  

 

版本有不一致没关系,这里我加载的是对应的最新的包。

项目中使用

项目中使用有两个地方要注意:

1.在Program.cs的程序入口要指定使用autofac容器

 public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseServiceProviderFactory(new AutofacServiceProviderFactory()) //指定使用autofac .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });

2.在Startup的启动文件中新增容器入口ConfigureContainer,默认方法及参数不得修改

 

 在这里我创建了一个接口ISay及实现方法Say,注入到容器中。

对应代码

public interface ISay { PeopleEntity SayHello(PeopleEntity peopleEntity); }[Intercept(typeof(InjectInterceptor))] public class Say : ISay { public PeopleEntity SayHello(PeopleEntity peopleEntity) { peopleEntity.Name = $"hello {peopleEntity.Name}"; return peopleEntity; } }

在这里我们使用的时候在控制器直接注入使用就行了

 

 

 在这里简单的使用autofac的容器使用就完成了。

下面我们来使用Castle来实现aop的使用

新建一个拦截器类,名为InjectInterceptor,而且必须要实现IInterceptor(该接口在Castle.DynamicProxy中),即Intercept虚方法,该方法将传递IInvocation接口参数。

public class InjectInterceptor : IInterceptor { public virtual void Intercept(IInvocation invocation) { PreProceed(invocation); invocation.Proceed(); Console.WriteLine(invocation.ReturnValue); PostProceed(invocation); } private void PreProceed(IInvocation invocation) { Console.WriteLine($"{DateTime.Now} interceptor invoke start"); } private void PostProceed(IInvocation invocation) { Console.WriteLine($"{DateTime.Now} interceptor invoke end"); } }

 

  在这里,我标记Say的方法,这里指明Intercept只能标记类或接口,不能标记特定的方法,所以你标记对应的类或接口时,内部的方法都会被拦截。

 [Intercept(typeof(InjectInterceptor))] public class Say : ISay

  在这里说明,这里是配合autofac使用的所以需要在Startup中的ConfigureContainer方法中注册拦截方法及注册这个Say方法时要开启允许方法拦截。

builder.RegisterType<InjectInterceptor>();builder.RegisterType<Say>().As<ISay>().EnableInterfaceInterceptors();

  嗯,就这样。

相关文章