Autofac 官方地址:https://autofaccn.readthedocs.io/en/latest/advanced/interceptors.html
(1)引用 nuget :Autofac.Extensions.DependencyInjection Autofac.Extras.DynamicProxy
(2)修改入口文件
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) //改用Autofac来实现依赖注入 .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
(3)修改startup 文件
//autofac 新增 public ILifetimeScope AutofacContainer { get; private set; } public void ConfigureContainer(ContainerBuilder builder) { }
(4)创建AOP拦截文件
using Castle.DynamicProxy; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; namespace WebApplication1.Aufac { public class CacheIntercept : IInterceptor { public CacheIntercept() { } public void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; Debug.WriteLine("before"); invocation.Proceed(); Debug.WriteLine("end"); } } }
(4)应用拦截效果
4-1 使用类进行AOP
4.1.1 创建以下类文件
using Autofac.Extras.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Aufac
{
/// <summary>
/// 类的AOP方式2
/// </summary>
[Intercept(typeof(CacheIntercept))]
public class AufacClass1
{
/// <summary>
/// 必须是virtual
/// </summary>
/// <returns></returns>
public virtual string GetName()
{
Debug.WriteLine("this is getname");
return "this is getname";
}
}
}
4.1.2配置startup 注入到服务
//autofac 新增
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterType<WebApplication1.Aufac.AufacClass2>().EnableClassInterceptors();
builder.Register(c => new WebApplication1.Aufac.CacheIntercept());
}
4.1.3在代码里调用 发现已经进行了拦截处理
调用代码如下
WebApplication1.Aufac.AufacClass2 face2;
public WeatherForecastController(WebApplication1.Aufac.AufacClass2 interFace1
)
{
face2 = interFace2;
}
[HttpGet]
//[Caching(AbsoluteExpiration =2,keyname ="id",keyvaluename ="id")]
public string Get()
{
face2.GetName();
return DateTime.Now.ToString();
}