Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

IServicesCollect Configure is not working, results in "Unable to resolve service for type"

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
        }
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading