I’m configuring JwtIssuerOptions using appsettings.json in a Asp.Net.Core api project (.NET 7), here is my code:
public class JwtIssuerOptions
{
public string Issuer { get; set; }
public string Audience { get; set; }
public string JwtSecretKey { get; set; }
}
public static void ConfigureJwt(this IServiceCollection services, ConfigurationManager configManager)
{
var jwtAppSettingOptions = configManager.GetSection(nameof(JwtIssuerOptions));
if (jwtAppSettingOptions == null)
{
throw new Exception("JwtIssuerOptions is null");
}
// jwtAppSettingOptions is not null
services.Configure<JwtIssuerOptions>(jwtAppSettingOptions);
// I have also tried the following:
services.Configure<JwtIssuerOptions>(setting => jwtAppSettingOptions.Bind(setting));
services.Configure<JwtIssuerOptions>(configManager.GetSection(nameof(JwtIssuerOptions)));
}
And I have a IdentityTokenClaimService depending on the JwtIssuerOptions :
public IdentityTokenClaimService(UserManager<ApplicationUser> userManager,
JwtIssuerOptions _jwtIssuerOptions)
{
_userManager = userManager;
this.jwtIssuerOptions = _jwtIssuerOptions;
}
When I build the project, it gives this error:
InvalidOperationException: Unable to resolve service for type 'JwtIssuerOptions' while attempting to activate 'IdentityTokenClaimService'.
>Solution :
Juding From the error message, you inject JwtIssuerOptions directly into your service.
You should inject IOptions<JwtIssuerOptions>/IOptionsSnapshot….. instead
For Example:
public class SomeService:ISomeService
{
private readonly IOptions<JwtIssuerOptions> _options;
SomeService(IOptions<JwtIssuerOptions> options)
{
_options = options;
}
}