Accessing IOptions<T> object .NET Core
To use some settings in
public void ConfigureServices(IServiceCollection services)
{
// Load the settings directly at startup.
var settings = Configuration.GetSection("Root:MySettings").Get<MySettings>();
// Verify mailSettings here (if required)
service.AddHangfire(
// use settings variable here
);
// If the settings needs to be injected, do this:
container.AddSingleton(settings);
}
In case you require your configuration object to be used inside an application component do not inject an IOptions<T>
into your component, because that only causes unforatunate downsides, as explained here. Instead, inject the value directly, as shown in the following example.
public class HomeController : Controller
{
private MySettings _settings;
public HomeController(MySettings settings)
{
_settings = settings;
}
}
You are close
services.Configure<MyOptions>(options => Configuration.GetSection("MyOptions").Bind(options));
You can now access your MyOptions using dependency injection
public class HomeController : Controller
{
private MySettings _settings;
public HomeController(IOptions<MySettings> settings)
{
_settings = settings.Value
// _settings.StringSetting == "My Value";
}
}
I took the snippets from this excellent article: https://andrewlock.net/how-to-use-the-ioptions-pattern-for-configuration-in-asp-net-core-rc2/ by Andrew Lock.