I am new to .NET Core and so apologies if this is a newbie question. I created a Web API project in .NET Core 2 using VS 2017.
For me, I have appsettings.json
file with some connection settings.
After reading about IOptions<T>
from microsoft tutorials, i am doing something like the following:
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<MyOptions>(Configuration);
// I want to access MyOptions object here to configure other services?how do i do that?
service.AddHangfire( // Get MyOptions.HangfireConenctionString etc.)
}
How do I access the created MYOptions
object in ConfigureServices
and also if I need to access it in Configure(IApplicationBuilder app,..)
method?
I only saw examples of injection IOptions<T>
in controllers in the tutorials.
IOptions is singleton and hence can be used to read configuration data within any service lifetime. Being singleton, it cannot read changes to the configuration data after the app has started. Run the app and hit the controller action. You should be able to see the values being fetched from the configuration file.
Use IOptionsSnapshot to read updated data IOptionsMonitor is a Singleton service that retrieves current option values at any time, which is especially useful in singleton dependencies. IOptionsSnapshot is a Scoped service and provides a snapshot of the options at the time the IOptionsSnapshot<T> object is constructed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With