.NET Core allows to lazily read settings from configuration file, de-serialize it to a POCO and register that POCO in built-in DI container with one line of code:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MyOptions>(Configuration.GetSection("MySection"));
}
Then any consumer can resolve IOptions<MyOptions>
to access that POCO:
public HomeController(IOptions<MyOptions> optionsAccessor)
{
MyOptions options = optionsAccessor.Value;
}
This approach has the significant disadvantages:
Unnecessary dependency from
Microsoft.Extensions.Options
package:Mocking, testing and explicit instance creation become a bit more verbose.
What is the easiest solution to resolve options without IOptions<T>
?
Deserialize options with
configuration.Get<TOptions>
orconfiguration.Bind
call and register a POCO in DI container explicitly as singleton:UPD: thanks to @NPNelson for
.Get<TOptions>()
hint.Then
IOptions<T>
resolving is no longer needed, and the class dependencies become clear:FYI: reading from an external service (database etc.) is also possible this way:
Remarks:
reloadOnChange
option setup:.AddJsonFile("appsettings.json", false, reloadOnChange: true)
);If you really need the file reload and you still don't want to use
IOptions
, consider a transient resolving. Of course, per-request resolving can lead to the significant perfomance decrease.You can just mock IOptions if you want to unit test services that depend on it. See this question and its answers. Depending on IOptions is still just depending on an interface, so it's not (or shouldn't be) making your code harder to test.