Naresh
Naresh

Reputation: 15

Get Value from appsettings.json file in common class

I want to get value using Appsettings from appsettings.json file

My code is in appsettings.json file:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AppSettings": {
    "APIURL": "https://localhost:44303/api"
  },
  "AllowedHosts": "*"
}

But I don't know how to get that value in common class file.

Upvotes: 0

Views: 879

Answers (2)

Kit
Kit

Reputation: 21749

Create a class matching the structure of your JSON, and put it in a "common" place:

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

Create an instance of AppSettings somewhere (what I like to do is create it in ConfigureServices and then register it with the container). For example

// create a new instance
var appsettings = new AppSettings();
// get section from the config served up by the various .NET Core configuration providers (including file JSON provider)
var section = Configuration.GetSection("AppSettings");
// bind (i.e. hydrate) the config to this instance
section.Bind(appsettings);
// make this object available to other services
services.AddSingleton(appsettings);

Then, when you need to use appsettings you can do so by simply injecting it into any services that need it. For example

public class SomeService
{
    private readonly AppSettings _settings;

    public SomeService(AppSettings settings) => _settings = settings;

    ...
}

Upvotes: 1

Chris Pratt
Chris Pratt

Reputation: 239440

In general, you want to use strongly-typed configuration. Essentially, you just create a class like:

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

And then, in ConfigureServices:

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

Then, where you need to use this, you'd inject IOptions<AppSettings>:

public class Foo
{
    private readonly IOptions<AppSetings> _settings;

    public Foo(IOptions<AppSettings> settings)
    {
        _settings = settings;
    }

    public void Bar()
    {
        var apiUrl = _settings.Value.ApiUrl;
        // do something;
    }
}

Upvotes: 1

Related Questions