I am creating a .Net Core (6.0) MVC application using NHibernate. When I try to build my solution I am getting an error:
System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: DiplomaWork.App.Services.IUserService Lifetime: Scoped ImplementationType: DiplomaWork.App.Services.UserService': Unable to resolve service for type 'NHibernate.ISession' while attempting to activate 'DiplomaWork.App.Services.UserService'.)'
and two inner errors ( InvalidOperationException) related to ISession. Please find below my
Program.cs
using DiplomaWork.App;
using DiplomaWork.App.Services;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
var configValue = builder.Configuration;
var authenticationSettings = new AuthenticationSettings();
configValue.GetSection("Authentication").Bind(authenticationSettings);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddSingleton(authenticationSettings);
builder.Services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = "Bearer";
option.DefaultScheme = "Bearer";
option.DefaultChallengeScheme = "Bearer";
}).AddJwtBearer(cfg =>
{
cfg.RequireHttpsMetadata = false;
cfg.SaveToken = true;
cfg.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = authenticationSettings.JwtIssuer,
ValidAudience = authenticationSettings.JwtIssuer,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authenticationSettings.JwtKey))
};
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
UserService.cs
using ISession = NHibernate.ISession;
using AutoMapper;
using DiplomaWork.App.Models;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.IdentityModel.Tokens.Jwt;
namespace DiplomaWork.App.Services
{
public class UserService : IUserService
{
private readonly ISession _session;
private readonly IMapper _mapper;
private readonly AuthenticationSettings _authenticationSettings;
public UserService(ISession session, IMapper mapper, AuthenticationSettings authenticationSettings)
{
_session = session;
_mapper = mapper;
_authenticationSettings = authenticationSettings;
}
public string GenerateJwt(LoginDto dto)
{
var user = _session.Query<Entities.User>().FirstOrDefault(x => x.Login == dto.Login);
if (user == null)
{
throw new Exception("Invalid login or password");
}
if (dto.Password != user.Password)
{
throw new Exception("Invalid login or password");
}
var claims = new List<Claim>()
{
new Claim(ClaimTypes.NameIdentifier, user.UserId.ToString()),
new Claim(ClaimTypes.Name, $"{user.Firstname}"),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_authenticationSettings.JwtKey));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var expires = DateTime.Now.AddMinutes(_authenticationSettings.JwtExpireMinutes);
var token = new JwtSecurityToken(_authenticationSettings.JwtIssuer,
_authenticationSettings.JwtIssuer,
claims,
expires: expires,
signingCredentials: credentials);
var tokenHandler = new JwtSecurityTokenHandler();
return tokenHandler.WriteToken(token);
}
public User GetUserById(long userId)
{
var userEntity = _session.Get<Entities.User>(userId);
if (userEntity == null) throw new Exception("User not found");
var user = _mapper.Map<User>(userEntity);
return user;
}
}
}
By the way, I cannot find fresh documentation for NHibernate so would be grateful for any links offering free help.