.net core 3.1 扩展 Autofac AOP
交流QQ群:555913397
有什么问题可以加群大家一起交流
1.添加Nuget程序包
1.1 Autofac.Extras.DynamicProxy
2.添加自定义AOP扩展类
//集成Autofac拦截器接口
public class AutofacAopExtension : IInterceptor
{
//实现拦截方法
public void Intercept(IInvocation invocation)
{
//执行方法前做的操作
Console.WriteLine("执行前");
//执行目标方法
invocation.Proceed();
//执行方法后做的操作
Console.WriteLine("执行后");
}
}
3.注册自定义AOP扩展
public class AutofacModule : Module
{
protected override void Load(ContainerBuilder builder)
{
//注册自定义AOP扩展
builder.Register(x => new AutofacAopExtension());
System.Reflection.Assembly serviceAssembly = System.Reflection.Assembly.Load("CoreMvc.Service");
System.Reflection.Assembly InterfaceAssembly = System.Reflection.Assembly.Load("CoreMvc.Interface");
builder.RegisterAssemblyTypes(serviceAssembly, InterfaceAssembly)
.Where(x => x.Name.EndsWith("AppService", StringComparison.OrdinalIgnoreCase))
//这里注意,有两种开启拦截的模式,算是一个小坑,上面的注册方式需要使用接口模式
//1.这是类模式
.EnableClassInterceptors()
//2.这是接口模式
.EnableInterfaceInterceptors()
//下面这是默认注入AOP,就不需要使用特性
.InterceptedBy(typeof(AutofacAopExtension))
.AsImplementedInterfaces();
}
}
4.添加拦截器特性实现AOP
//添加拦截器特性
[Intercept(typeof(AutofacAopExtension))]
public class PeopleAppService : IPeopleAppService
{
public void Show()
{
Console.WriteLine("People");
}
}
}
5.测试AOP
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IPeopleAppService _people;
private readonly ICompanyAppService _company;
public HomeController(ILogger<HomeController> logger, IPeopleAppService people, ICompanyAppService company)
{
_logger = logger;
_people = people;
_company = company;
}
public IActionResult Index()
{
//调用此方法
_people.Show();
_company.Show();
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
6.使用效果
执行前
People
执行后
执行前
Company
执行后