.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