.NetCore Autofac依賴注入獲取注冊后的實例、全局容器獲取


有的時候我們需要在自己創建的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>();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM