有的时候我们需要在自己创建的AOP上面使用接口,比如我使用了Aspect-Injector,Aspect-Injector的自定义切面继承了Attribute,没办法在构造函数注入,这时候就可以用到依赖注入注册后的实例了。
新建一个类,类里面有一个静态的ILifetimeScope来保存注入后的实例,每次我们只要获取这个ILifetimeScope就可以了
AutofacUtil类:
1 /// <summary> 2 /// Autofac依赖注入服务 3 /// </summary> 4 public class AutofacUtil 5 { 6 /// <summary> 7 /// Autofac依赖注入静态服务 8 /// </summary> 9 public static ILifetimeScope Container { get; set; } 10 11 /// <summary> 12 /// 获取服务(Single) 13 /// </summary> 14 /// <typeparam name="T">接口类型</typeparam> 15 /// <returns></returns> 16 public static T GetService<T>() where T : class 17 { 18 return Container.Resolve<T>(); 19 } 20 21 /// <summary> 22 /// 获取服务(请求生命周期内) 23 /// </summary> 24 /// <typeparam name="T">接口类型</typeparam> 25 /// <returns></returns> 26 public static T GetScopeService<T>() where T : class 27 { 28 return (T)GetService<IHttpContextAccessor>().HttpContext.RequestServices.GetService(typeof(T)); 29 } 30 }
然后在Configure添加
AutofacUtil.Container = app.ApplicationServices.GetAutofacRoot();
/// <summary> /// Configure /// </summary> /// <param name="app"></param> /// <param name="env"></param> /// <param name="loggerFactory"></param> public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) { #region Autofac依赖注入服务 AutofacUtil.Container = app.ApplicationServices.GetAutofacRoot(); #endregion }
使用方法
T temp = AutofacUtil.GetScopeService<T>();