[英]Access configuration object (appsettings.json) in library project
I started a .net core web api project.我启动了一个 .net 内核 web api 项目。 I have one solution with the main project and many other project like DAL, Common etc.
我有一个主要项目和许多其他项目(如 DAL、Common 等)的解决方案。
I want to create a class in the Common project that will share configuration settings(appsettings.json) between my different library project.我想在 Common 项目中创建一个 class ,它将在我的不同库项目之间共享配置设置(appsettings.json)。 So, How can I acces Iconfiguration from that class?
那么,如何从 class 访问 Iconfiguration?
Is this a good way to do this?这是一个好方法吗? Or should I create a class into the main project to get configuration data from other project?
或者我应该在主项目中创建一个 class 以从其他项目获取配置数据?
One way to do it would be to create a Configuration Model based on your section/subsection from your appsettings.json file, add the configuration section in your Startup.cs class, then you can use the built-in dependency injection to inject the configuration anywhere you would need it.一种方法是根据 appsettings.json 文件中的部分/子部分创建配置 Model,在 Startup.cs class 中添加配置部分,然后您可以将配置注入到内置的依赖项注入中任何你需要它的地方。
For Example例如
appsettings.json: appsettings.json:
{
"MyConfiguration" : {
"Configuration1" : "1",
}
}
Your configuration model:您的配置 model:
public class MyConfiguration
{
public int Configuration1 { get; set; }
}
Then in the StartupClass in the ConfigureServices method you have to add然后在 ConfigureServices 方法的 StartupClass 中,您必须添加
services.Configure<MyConfiguration>(configuration.GetSection("MyConfiguration"));
services.AddOptions();
And when you want to use that Configuration somewhere in the code, you would just inject it in the constructor like so:当您想在代码中的某处使用该配置时,您只需将其注入构造函数中,如下所示:
public class SomeClass
{
private MyConfiguration MyConfiguration { get; }
public SomeClass(IOptions<MyConfiguration> myConfigurationOptions)
{
MyConfiguration = myConfigurationOptions.Value;
}
//... more code
}
Then you can access it然后就可以访问了
MyConfiguration.Configuration1
You can add the file as a link
in yout project.您可以将该文件
as a link
添加到您的项目中。
"Add" ->"Existing Item..."
"Add" ->"Existing Item..."
Add As Link
".Add As Link
”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.