本文介绍了从类库访问Asp.net-core中的appsetting.json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从类库访问 appsetting.json 文件。到目前为止,我找到的解决方案是从 Microsoft.Extensions.Configuration 创建一个实现接口 IConfiguration 的配置类,并添加

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");

这似乎是一个糟糕的选择,因为每次访问文件时我们都必须添加json文件appsetting配置。我们没有其他选择,例如 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": "[email protected];[email protected]"
}

匹配模型类

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 07:30