How to get IOptions in ConfigureServices method or pass IOptions into extension method?
For binding data from appsettings.json
to Model
, you could follow steps below:
Appsettings.json content
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }, "JWT": { "Issuer": "I", "Key": "K" } }
JWT Options
public class JwtOptions { public string Issuer { get; set; } public string Key { get; set; } }
Startup.cs
public void ConfigureServices(IServiceCollection services) { services.Configure<JwtOptions>(Configuration.GetSection("JWT")); var serviceProvider = services.BuildServiceProvider(); var opt = serviceProvider.GetRequiredService<IOptions<JwtOptions>>().Value; services.AddJwtAuthentication(opt.Issuer, opt.Key); services.AddMvc(); }
One more option to pass
JwtOptions
directly.public void ConfigureServices(IServiceCollection services) { services.Configure<JwtOptions>(Configuration.GetSection("JWT")); var serviceProvider = services.BuildServiceProvider(); var opt = serviceProvider.GetRequiredService<IOptions<JwtOptions>>().Value; services.AddJwtAuthentication(opt); services.AddMvc(); }
Change the extension method.
public static IServiceCollection AddJwtAuthentication(this IServiceCollection services, JwtOptions opt)
One other option is to bind the configurations to a class with the Bind()
extension. (IMO this a more clean solution then the IOptions)
public class JwtKeys
{
public string Issuer { get; set; }
public string Key { get; set; }
}
public void ConfigureServices(IServiceCollection services)
{
var jwtKeys = new JwtKeys();
Configuration.GetSection("JWT").Bind(JwtKeys);
services.AddJwtAuthentication(jwtKeys);
}
public static IServiceCollection AddJwtAuthentication(this IServiceCollection services, JwtKeys jwtKeys)
{....}
Then if you need the JwtKeys settings some other place in the solution, just register the class on the collection and inject it where needed
services.AddSingleton(jwtKeys);