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

时间:2016-04-27 14:48:00

标签: c# .net dependency-injection asp.net-core

在我的一个具体课堂上。我有方法。

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;
    }

现在我将网址放入appsettings.json。

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

我创建了Startup.cs

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

        Configuration = builder.Build();
    }
}

现在我卡住了。

修改

顺便说一下,我没有控制器,它是一个控制台应用程序。

3 个答案:

答案 0 :(得分:3)

创建一个静态类

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

然后在任何地方访问设置

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

appsettings.json示例

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

答案 1 :(得分:3)

从appSettings.json读取配置的首选方法是使用依赖注入和内置或(或第三方)IoC容器。您只需将配置部分传递给Configure方法即可。

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

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

这样您就不必手动设置值或初始化AppSettings类。

并在您的服务中使用它:

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;
    }
}

IoC Container也可以在控制台应用程序中使用,您只需自己引导它即可。 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
    } 
}

答案 2 :(得分:1)

您可以访问IConfigurationRoot中的数据,如下所示:

Configuration["AppSettings:uri"]

与评论中建议的一样,我会将信息放在该信息的单独类中,并将其传递到DI容器中。

班级

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

<强> DI

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

<强>控制器

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