Adding .settings to .NET Core project

2.3k Views Asked by At

Is it possible to add a .settings file to .NET Core projects in Visual Studio? If not, what's the equivalent/alternative way to achieve this with .NET Core?

1

There are 1 best solutions below

0
Will Ray On BEST ANSWER

You can add strongly-typed values into the IOC container from the appsettings file:

appsettings.json

{
  // ...other stuff...
  "MyConfiguration": {
    "ValueOne": "Some value",
    "ValueTwo": "2"
  }
}

MyConfiguration.cs

public class MyConfiguration
{
    public string ValueOne { get; set; }

    public int ValueTwo { get; set; }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    services.AddOptions();
    services.Configure<MyConfiguration>(Configuration.GetSection("MyConfiguration"));
}

You can then get them by requesting IOptions<MyConfiguration>, like so:

public class HomeController : Controller
{
    public HomeController(IOptions<MyConfiguration> config)
    {
        var someValue = config.Value.ValueOne; // "Some value"
    }
}