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