"Unable to resolve service for type ... while attempting to activate "
Прохожу сейчас туториал metanit'а по управлению ролями в Identity. Сделал всё согласно уроку, однако при попытке вызвать RolesController получаю следующую ошибку:
InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]' while attempting to activate 'Diplom1.Controllers.RolesController'.
Возможно проблема в конфигурации сервисов в Startup, но у меня нет никаких идей на этот счёт.
RolesController:
public class RolesController : Controller
{
RoleManager<IdentityRole> _roleManager;
UserManager<User> _userManager;
public RolesController(RoleManager<IdentityRole> roleManager, UserManager<User> userManager)
{
_roleManager = roleManager;
_userManager = userManager;
}
public IActionResult Index() => View(_roleManager.Roles.ToList());
public IActionResult Create() => View();
[HttpPost]
public async Task<IActionResult> Create(string name)
{
if (!string.IsNullOrEmpty(name))
{
IdentityResult result = await _roleManager.CreateAsync(new IdentityRole(name));
if (result.Succeeded)
{
return RedirectToAction("Index");
}
else
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
}
return View(name);
}
[HttpPost]
public async Task<IActionResult> Delete(string id)
{
IdentityRole role = await _roleManager.FindByIdAsync(id);
if (role != null)
{
IdentityResult result = await _roleManager.DeleteAsync(role);
}
return RedirectToAction("Index");
}
public IActionResult UserList() => View(_userManager.Users.ToList());
public async Task<IActionResult> Edit(string userId)
{
User user = await _userManager.FindByIdAsync(userId);
if (user != null)
{
var userRoles = await _userManager.GetRolesAsync(user);
var allRoles = _roleManager.Roles.ToList();
ChangeRoleViewModel model = new ChangeRoleViewModel
{
UserId = user.Id,
UserEmail = user.Email,
UserRoles = userRoles,
AllRoles = allRoles
};
return View(model);
}
return NotFound();
}
[HttpPost]
public async Task<IActionResult> Edit(string userId, List<string> roles)
{
// получаем пользователя
User user = await _userManager.FindByIdAsync(userId);
if (user != null)
{
var userRoles = await _userManager.GetRolesAsync(user);
var allRoles = _roleManager.Roles.ToList();
var addedRoles = roles.Except(userRoles);
var removedRoles = userRoles.Except(roles);
await _userManager.AddToRolesAsync(user, addedRoles);
await _userManager.RemoveFromRolesAsync(user, removedRoles);
return RedirectToAction("UserList");
}
return NotFound();
}
}
Конфигурация Identity в Startup:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
Ответы (1 шт):
Благодаря ссылкам комментаторов получилось забороть проблему.
В Startup оказалось достаточно добавить .AddRoles<IdentityRole>()
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
В самом контроллере все ссылки на модель User заменил на IdentityUser.