c# - 如何在本地创建 IConfiguration 实例?

标签 c# asp.net-core dependency-injection .net-core

我想问一下如何创建 ASP.NET Core 配置的实例,这与我在知道 appsettings.json 的 Controller 构造函数中需要它时创建的实例相同。文件

喜欢 _config = ActivatorUtilities.CreateInstance<IConfiguration>(null);

System.InvalidOperationException: 'A suitable constructor for type 'Microsoft.Extensions.Configuration.IConfiguration' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.'



这是有道理的,因为它是接口(interface),但它在 Controller 的 Constructor 案例中是如何工作的呢?我怎样才能创建一个实例?

我正在使用 MS DI

谢谢

最佳答案

您可以创建一个本地配置实例,如下所示。

IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath([PATH_WHERE_appsettings.json_RESIDES])
            .AddJsonFile("appsettings.json")
            .Build();

如需更多信息,请参阅 Configuration in ASP.NET Core

关于c# - 如何在本地创建 IConfiguration 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56732820/

相关文章:

c# - 如何从打开的流中检测文件重命名

c# - 协助 UI Dispatcher 处理大量的方法调用

c# - ASP.NET Core - 无法在属性 '1' 上设置类型 'System.Int32' 的默认值 'MerchantStatus'

javascript - AngularJS 函数 DI 参数

重命名包后未加载 symfony2 包扩展

c# - 在 Entity Framework 5 中创建模拟上下文时遇到问题

c# - 查看已安装设备的端口地址和属性

c# - 整洁架构和 Asp.Net 核心标识

asp.net-core - 在 Google 身份验证后面提供静态文件

dependency-injection - 如何使用 Unity 在每次处理旧实例时解析新实例