简体   繁体   English

如何在本地创建IConfiguration实例?

[英]How can I create an instance of IConfiguration locally?

I'd want to ask how to create an instance of ASP.NET Core's Configuration, the same that's being created when I require it in Controller's constructor which knows about the appsettings.json file 我想问一下如何创建ASP.NET Core的Configuration实例,该实例与我在知道appsettings.json文件的Controller的构造函数中需要它时所创建的实例相同

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

System.InvalidOperationException: 'A suitable constructor for type 'Microsoft.Extensions.Configuration.IConfiguration' could not be located. System.InvalidOperationException:'找不到类型'Microsoft.Extensions.Configuration.IConfiguration'的合适的构造函数。 Ensure the type is concrete and services are registered for all parameters of a public constructor.' 确保类型是具体的,并为公共构造函数的所有参数注册服务。

It makes sense because it is interface, but how it does work in Controller's Constructor case? 这是有道理的,因为它是接口,但是在Controller的Constructor情况下它如何工作? and how can I create an instance of that? 以及如何创建它的实例?

I'm using MS DI 我正在使用MS DI

Thanks 谢谢

You can create a local instance of configuration as shown below. 您可以创建本地配置实例,如下所示。

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

For further information see Configuration in ASP.NET Core 有关更多信息,请参见ASP.NET Core中的配置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM