Wyjątek System.AggregateException oraz InvalidOperationException w Asp.Net Core 6.0

0

Podczas wysyłania żądania w Postmanie dla metody post pojawiają się następujące błędy:

System.AggregateException: „Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: RestaurantApp.Services.IAccountService Lifetime: Scoped ImplementationType: RestaurantApp.Services.AccountService': Unable to resolve service for type 'RestaurantApp.AuthenticationSettings' while attempting to activate 'RestaurantApp.Services.AccountService'.)”

InvalidOperationException: Unable to resolve service for type 'RestaurantApp.AuthenticationSettings' while attempting to activate 'RestaurantApp.Services.AccountService'.

Oto kod:

public class AccountService : IAccountService
{
    private readonly RestaurantDbContext _dbContext;
    private readonly IPasswordHasher<User> _passwordHasher;
    private readonly AuthenticationSettings _authenticationSettings;

    public AccountService(RestaurantDbContext dbContext, IPasswordHasher<User> passwordHaser, AuthenticationSettings authenticationSettings)
    {
        _dbContext = dbContext;
        _passwordHasher = passwordHaser;
        _authenticationSettings = authenticationSettings;
    }

    public void RegisterUser(RegisterUserDto dto)
    {
        var newUser = new User()
        {
            Email = dto.Email,
            DateOFbirth = dto.DateOFbirth,
            Nationality = dto.Nationality,
            RoleId = dto.RoleId
        };

        var hashedPassword = _passwordHasher.HashPassword(newUser, dto.Password);
        newUser.PasswordHash = hashedPassword;

        _dbContext.Users.Add(newUser);
        _dbContext.SaveChanges();
    }

    public string GenerateJwt(LoginDto dto)
    {
        var user = _dbContext.Users
            .Include(u => u.Role)
            .FirstOrDefault(u => u.Email == dto.Email);

        if(user is null)
        {
            throw new BadHttpRequestException("Invalid Email or Password");
        }

        var result = _passwordHasher.VerifyHashedPassword(user, user.PasswordHash, dto.Password);

        if(result == PasswordVerificationResult.Failed)
        {
            throw new BadHttpRequestException("Invalid Email or Password");
        }

        var claims = new List<Claim>()
        {
            new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
            new Claim(ClaimTypes.Name, $"{user.FirstName} {user.LastName}" ),
            new Claim(ClaimTypes.Role, $"{user.Role.Name}"),
            new Claim("DateOfBirth", $"{user.DateOFbirth.Value.ToString("yyyy-MM-dd")}"),
            new Claim("Nationality", user.Nationality)
        };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_authenticationSettings.JwtKey));
        var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
        var expires = DateTime.Now.AddDays(_authenticationSettings.JwtExpireDays);

        var token = new JwtSecurityToken(_authenticationSettings.JwtIssuer,
            _authenticationSettings.JwtIssuer, claims,
            expires: expires,
            signingCredentials: cred);

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}        ```

```  public interface IAccountService
{
    void RegisterUser(RegisterUserDto dto);
    string GenerateJwt(LoginDto dto);
}   ```


``` public class AuthenticationSettings
{
    public string JwtKey { get; set; }
    public int JwtExpireDays { get; set; }
    public string JwtIssuer { get; set; }
}   ```

i w Program.cs:

``` builder.Services.AddScoped<IAccountService, AccountService>();   ```
1

Unable to resolve service wskazywałoby na brak rejestracji serwisu w AppBuilder lub nadmiarową rejestrację.

1

@Sandra: Myślałem właśnie o tym. Coś takiego dodać? builder.Services.AddScoped<AuthenticationSettings>();

1

Dobra działa. Dzięki.

1 użytkowników online, w tym zalogowanych: 0, gości: 1