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 內容了