.NetCore Autofac依赖注入获取注册后的实例
2021-02-16 10:18
阅读:678
标签:life ESS 注册 sum builder 自定义 access ram ati
有的时候我们需要在自己创建的AOP上面使用接口,比如我使用了Aspect-Injector,Aspect-Injector的自定义切面继承了Attribute,没办法在构造函数注入,这时候就可以用到依赖注入注册后的实例了。
新建一个类,类里面有一个静态的ILifetimeScope来保存注入后的实例,每次我们只要获取这个ILifetimeScope就可以了
AutofacUtil类:
1 ///2 /// Autofac依赖注入服务 3 /// 4 public class AutofacUtil 5 { 6 /// 7 /// Autofac依赖注入静态服务 8 /// 9 public static ILifetimeScope Container { get; set; } 10 11 /// 12 /// 获取服务(Single) 13 /// 14 /// 接口类型 15 /// 16 public static T GetService () where T : class 17 { 18 return Container.Resolve (); 19 } 20 21 /// 22 /// 获取服务(请求生命周期内) 23 /// 24 /// 接口类型 25 /// 26 public static T GetScopeService () where T : class 27 { 28 return (T)GetService ().HttpContext.RequestServices.GetService(typeof(T)); 29 } 30 }
然后在Configure添加
AutofacUtil.Container = app.ApplicationServices.GetAutofacRoot();
////// Configure /// /// /// /// public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory) { #region Autofac依赖注入服务 AutofacUtil.Container = app.ApplicationServices.GetAutofacRoot(); #endregion }
使用方法
T temp = AutofacUtil.GetScopeService();
.NetCore Autofac依赖注入获取注册后的实例
标签:life ESS 注册 sum builder 自定义 access ram ati
原文地址:https://www.cnblogs.com/weijunyu/p/12974927.html
文章来自:搜素材网的编程语言模块,转载请注明文章出处。
文章标题:.NetCore Autofac依赖注入获取注册后的实例
文章链接:http://soscw.com/index.php/essay/56045.html
文章标题:.NetCore Autofac依赖注入获取注册后的实例
文章链接:http://soscw.com/index.php/essay/56045.html
评论
亲,登录后才可以留言!