.net core3.1 類庫下從容器中獲取IConfiguration 實例


core版本從2.0升級3.1時,項目框架底層獲取“IConfiguration ”實例報錯

2.0版本寫法是:

public static T GetServiceFromCollection<T>(this IServiceCollection services)

{
return (T)services
 .LastOrDefault(p => p.ServiceType == typeof(T))?
.ImplementationInstance;
} 可以正常運行,ImplementationInstance 不為空,能正常獲取到實例

 

3.1版本下  ImplementationInstance 為null,研究了一下是3.1版本在項目啟動時  IConfiguration  注冊方式變更了,改變寫法如下:

public static T GetServiceFromCollection<T>(this IServiceCollection services)
{
var con= services.LastOrDefault(p => p.ServiceType == typeof(T)).ImplementationFactory;
return (T)con.Invoke(null);
}

可以正常獲取到 IConfiguration 實例,繼續獲取 appsettings.json 內容了


免責聲明!

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



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