AutoFac實現AOP擴充套件
阿新 • • 發佈:2022-04-10
1.nuget包
2.用autoFuc替代原來的IOC容器。
program類中修改程式碼
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
新增動態代理類
public class CustomAutofacCacheInterceptor : IInterceptor { private IDistributedCache _iDistributeCache; public CustomAutofacCacheInterceptor(IDistributedCache distributeCache) { this._iDistributeCache = distributeCache; }public void Intercept(IInvocation invocation) { string key = $"{invocation.Method}_{string.Join(",", invocation.Arguments)}"; string result = this._iDistributeCache.GetString(key); if (string.IsNullOrEmpty(result)) { invocation.Proceed(); //實際執行的方法this._iDistributeCache.SetString(key,Convert.ToString(invocation.ReturnValue) //設定快取, , new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(20) }); } else { invocation.ReturnValue = Convert.ChangeType(result, invocation.Method.ReturnType); //取快取 } } }
startup類中修改程式碼
public void ConfigureContainer(ContainerBuilder containerBuilder) { containerBuilder.RegisterType<UserService>().As<IUserService>().EnableInterfaceInterceptors() .InterceptedBy(typeof(CustomAutofacCacheInterceptor)); containerBuilder.RegisterType<CustomAutofacCacheInterceptor>(); }
當執行UserService類中的方法時,會走代理類。實際執行的方法為invocation.Proceed();