简体   繁体   English

从1.0.0-rc1-final中的appsettings.json读取一个值

[英]Read a value from appsettings.json in 1.0.0-rc1-final

In one of my concrete class. 在我的一个具体课堂上。 I have the method. 我有方法。

public class Call : ICall
{
    ......
    public  Task<HttpResponseMessage> GetHttpResponseMessageFromDeviceAndDataService()
    {
        var client = new HttpClient();
        var uri = new Uri("http://localhost:30151");
        var response =  GetAsyncHttpResponseMessage(client, uri);
        return response;
    }

Now I put the url into appsettings.json. 现在我将url放入appsettings.json。

{
    "AppSettings": {
       "uri": "http://localhost:30151"
    }
 }

And I created a Startup.cs 我创建了一个Startup.cs

 public class Startup
{
    public IConfiguration Configuration { get; set; }
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json");

        Configuration = builder.Build();
    }
}

and now I get stuck. 现在我卡住了

EDIT 编辑

By the way, I don't have a controller, it is a console application. 顺便说一句,我没有控制器,它是一个控制台应用程序。

Create a static class 创建一个静态类

public static class AppSettings
{
    public static IConfiguration Configuration { get; set; }

    public static T Get<T>(string key)
    {
        if (Configuration == null)
        {
            var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
            var configuration = builder.Build();
            Configuration = configuration.GetSection("AppSettings");
        }

        return (T)Convert.ChangeType(Configuration[key], typeof(T));
    }
}

then access the settings anywhere you want like 然后在任何地方访问设置

var uri = AppSettings.Get<string>("uri"); 
var rooms = AppSettings.Get<int>("noRooms");

appsettings.json example appsettings.json示例

{
    "AppSettings": {
        "uri": "http://localhost:30151",
        "noRooms":  100
    }
}

The preferred way to read configuration from appSettings.json is using dependency injection and the built or (or 3rd party) IoC container. 从appSettings.json读取配置的首选方法是使用依赖注入和内置或(或第三方)IoC容器。 All you need is to pass the configuration section to the Configure method. 您只需将配置部分传递给Configure方法即可。

public class AppSettings
{
    public int NoRooms { get; set; }
    public string Uri { get; set; }
}

services.Configure<AppSettings>(Configuration.GetSection("appsettings"));

This way you don't have to manually set the values or initialize the AppSettings class. 这样您就不必手动设置值或初始化AppSettings类。

And use it in your service: 并在您的服务中使用它:

public class Call : ICall
{
    private readonly AppSettings appSettings;

    public Call(IOptions<AppSettings> appSettings) 
    {
        this.appSettings = appSetings.Value;
    }

    public Task<HttpResponseMessage>GetHttpResponseMessageFromDeviceAndDataService()
    {
        var client = new HttpClient();
        var uri = new Uri(appSettings.Uri);
        var response =  GetAsyncHttpResponseMessage(client, uri);
        return response;
    }
}

The IoC Container can also be used in a console application, you just got to bootstrap it yourself. IoC容器也可以在控制台应用程序中使用,您只需自己引导它。 The ServiceCollection class has no dependencies and can be instantiated normally and when you are done configuring, convert it to an IServiceProvider and resolve your main class with it and it would resolve all other dependencies. ServiceCollection类没有依赖关系,可以正常实例化,当您完成配置后,将其转换为IServiceProvider并使用它解析主类,它将解析所有其他依赖项。

public class Program
{
    public static void Main(string[] args) 
    {
        var configurationBuilder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json");
        var configuration = configurationBuilder.Build()
            .ReloadOnChanged("appsettings.json");

        var services = new ServiceCollection();
        services.Configure<AppSettings>(configuration.GetSection("appsettings"));
        services.AddTransient<ICall, Call>();
        // add other services

        // after configuring, build the IoC container
        IServiceProvider provider = services.BuildServiceProvider();

        Program program = provider.GetService<Program>();

        // run the application, in a console application we got to wait synchronously
        program.Wait();
    }

    private readonly ICall callService;
    // your programs main entry point
    public Program(ICall callService) 
    {
        this.callService = callService;
    }

    public async Task Run()
    {
         HttpResponseMessage result = await call.GetHttpResponseMessageFromDeviceAndDataService();

         // do something with the result
    } 
}

You can access data from the IConfigurationRoot as following: 您可以从IConfigurationRoot访问数据,如下所示:

Configuration["AppSettings:uri"]

Like suggested in the comment I would put the information in a seperate class for that info and pass it into the DI container. 像评论中建议的那样,我会将信息放在该信息的单独类中,并将其传递到DI容器中。

the class 班级

public class AppSettings {
    public string Uri { get; set; }
}

DI DI

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<AppSettings>(new AppSettings() { Uri = Configuration["AppSettings:uri"] });
    // ...
}

Controller 调节器

public class DemoController
{
    public HomeController(IOptions<AppSettings> settings) 
    {
       //do something with it
    }
}

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

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