问题描述
我正在尝试从类库访问 appsetting.json
文件.到目前为止,我找到的解决方案是从 Microsoft.Extensions.Configuration
创建一个实现接口 IConfiguration
的配置类,并将 json 文件添加到类并从中读取.
I am trying to access appsetting.json
file from a class library. So far the solution that I found is to create a configuration class implementing interface IConfiguration
from Microsoft.Extensions.Configuration
and add the json file to class and read from the same.
var configuration = new Configuration();
configuration.AddJsonFile("appsetting.json");
var connectionString= configuration.Get("connectionString");
这似乎是一个不好的选择,因为我们每次必须访问 appsetting 配置时都必须添加 json 文件.我们在 ASP.NET 中没有像 ConfigurationManager
这样的替代方案吗?
This seems to be bad option as we have to add the json file each time we have to access the appsetting configuration. Dont we have any alternative like ConfigurationManager
in ASP.NET.
推荐答案
我假设您想从 Web 应用程序访问 appsettings.json
文件,因为类库没有 appsettings.json
默认.
I'm assuming you want to access the appsettings.json
file from the web application since class libraries don't have an appsettings.json
by default.
我创建了一个模型类,它的属性与 appsettings.json
中某个部分的设置相匹配.
I create a model class that has properties that match the settings in a section in appsettings.json
.
appsettings.json 中的部分
"ApplicationSettings": {
"SmtpHost": "mydomain.smtp.com",
"EmailRecipients": "me@mydomain.com;other@mydomain.com"
}
匹配模型类
namespace MyApp.Models
{
public class AppSettingsModel
{
public string SmtpHost { get; set; }
public string EmailRecipients { get; set; }
}
}
然后填充该模型类并将其添加到 DI 容器中的 IOptions
集合中(这是在 Startup 类的 Configure()
方法中完成的).
Then populate that model class and add it to the IOptions
collection in the DI container (this is done in the Configure()
method of the Startup class).
services.Configure<AppSettingsModel>(Configuration.GetSection("ApplicationSettings"));
// Other configuration stuff
services.AddOptions();
然后,您可以从框架调用的任何方法访问该类,方法是将其添加为构造函数中的参数.框架负责查找类并将其提供给构造函数.
Then you can access that class from any method that the framework calls by adding it as a parameter in the constructor. The framework handles finding and providing the class to the constructor.
public class MyController: Controller
{
private IOptions<AppSettingsModel> settings;
public MyController(IOptions<AppSettingsModel> settings)
{
this.settings = settings;
}
}
然后当类库中的方法需要设置时,我要么单独传递设置,要么传递整个对象.
Then when a method in a class library needs the settings, I either pass the settings individually or pass the entire object.
这篇关于在 Asp.net-core 中从类库访问 appsetting.json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!