dotnetcore - pull settings from appsettings into IOptions<t>

April 28, 2017

It's easy to add new configuration sections in your dotnetcore application's appsettings.json, simply add your new section and add a configuration middleware. Start by adding a new section name and json sub properties.

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "smtp": {
    "host": "example.mail.com",
    "port": 25
    "email": "example@mail.com",
    "password": "p@ssw0rd",
    "host": true
  }
}

Setup a new class that will be used to bind the json properties to class properties matching on names. For folder structure, create an Options folder and create the new SmtpOptions.cs in that folder.

public class StmpOptions
{
    public string Host { get; set; }
    public int Port { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public bool IsHtml { get; set; }
}

Then wire up the middleware to bind to that specific section.

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

Lastly, inject the IOptions<t> into your controllers, services, or other classes that depend on it that are injected through dotnetcore's DI. You'll want to save that off as a readonly field for use throughout your class.

public class ValuesController : Controller
{
        private readonly IOptions<SmtpOptions> _smtpOptions;

        public ValuesController(IOptions<SmtpOptions> smtpOptions)
        {
            _smtpOptions = smtpOptions;
        }
}

 

Share

Comments