如何在本地创建 IConfiguration 的实例? [英] How can I create an instance of IConfiguration locally?
问题描述
我想问一下如何创建 ASP.NET Core 配置的实例,这与我在知道 appsettings.json
文件的 Controller 的构造函数中需要它时创建的实例相同>
like _config = ActivatorUtilities.CreateInstance
System.InvalidOperationException: '找不到适合类型 'Microsoft.Extensions.Configuration.IConfiguration' 的构造函数.确保类型是具体的,并且为公共构造函数的所有参数注册了服务.'
这是有道理的,因为它是接口,但它在控制器的构造函数情况下是如何工作的呢?以及如何创建一个实例?
我正在使用 MS DI
谢谢
您可以创建一个本地的配置实例,如下所示.
IConfigurationRoot configuration = new ConfigurationBuilder().SetBasePath([PATH_WHERE_appsettings.json_RESIDES]).AddJsonFile("appsettings.json").建造();
有关详细信息,请参阅 ASP 中的配置.NET 核心
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
like _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.'
It makes sense because it is interface, but how it does work in Controller's Constructor case? and how can I create an instance of that?
I'm using 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
这篇关于如何在本地创建 IConfiguration 的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!