How to get IOptions in ConfigureServices method?
I have asp.net core application. I want to use IOptions
pattern to inject values from appsettings.json. So I have a class SecurityHeaderOptions
, and also have target class SecurityHeadersBuilder
whose constructor takes IOptions<SecurityHeaderOptions>
as parameter.
I know that .net core can implicitly create instance of SecurityHeadersBuilder
by injecting IOptions<SecurityHeaderOptions>
after registering both with container.
However i want to explicitly create instance of SecurityHeadersBuilder
, call one of its method and then register the instance with the container.
public sealed class SecurityHeaderOptions
{
public string FrameOption { get; set; }
public string XssProtection { get; set; }
}
public class SecurityHeadersBuilder
{
private readonly SecurityHeaderOptions _options = null;
public SecurityHeadersBuilder(IOptions<SecurityHeaderOptions> options)
{
_options = options.Value;
}
public SecurityHeadersBuilder AddDefaultPolicy()
{
AddFrameOptions();
AddConetntSecurityPolicy();
return this;
}
}
ConfigureServices method
public void ConfigureServices(IServiceCollection services)
{
services.Configure<SecurityHeaderOptions>(Configuration.GetSection("SecurityHeaderOptions"));
services.AddScoped<SecurityHeadersBuilder>(provider =>
new SecurityHeadersBuilder(?????).AddDefaultPolicy())
}
Questions
1> If i am explicitly passing options into constructor, do i need to register SecurityHeaderOptions
with the container using service.Configure
method?
2> Configuration.GetSection("SecurityHeaderOptions")
can't return instance of IOptions<SecurityHeaderOptions>
, instead it returns IConfigurationSection
?
3>Either way, how do I retrieve and pass SecurityHeaderOptions
into SecurityHeadersBuilder
's constructor?
Solution 1:
Using .NET Core 2 and not having a provider available (or caring to add it) in ConfigureServices
I opted to go with something like this (using OP code as example):
public void ConfigureServices(IServiceCollection services)
{
// secOpts available for use in ConfigureServices
var secOpts = Configuration
.GetSection("SecurityHeaderOptions")
.Get<SecurityHeaderOptions>();
...
}
Solution 2:
This is how I register options and inject into SecurityHeadersBuilder
public void ConfigureServices(IServiceCollection services)
{
services.Configure<SecurityHeaderOptions>(Configuration.GetSection("SecurityHeaderOptions"));
services.AddScoped<SecurityHeadersBuilder>(provider =>
{
var option = provider.GetService<IOptions<SecurityHeaderOptions>>();
return new SecurityHeadersBuilder(option)
.AddDefaultPolicy();
});
}