Reputation: 33
I hope that you are all doing well! I am getting the following error:
InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'july_15_auth.Controllers.AccountController'
I have spent weeks trying to solve the error, reading the forums here, and other websites. The comments online have suggested to modify my Startup.cs file, but I have tried many different ways, yet I still cannot figure out why this is not work. Any suggestions would be greatly appreciated.
This is my AccountController file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using july_15_auth.Models;
using july_15_auth.ViewModels;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace july_15_auth.Controllers
{
public class AccountController : Controller
{
private readonly UserManager<IdentityUser> userManager;
private readonly SignInManager<IdentityUser> signInManager;
private readonly RoleManager<IdentityUser> roleManager;
public AccountController(UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager, RoleManager<IdentityUser> roleManager)
{
this.userManager = userManager;
this.signInManager = signInManager;
this.roleManager = roleManager;
}
[AcceptVerbs("Get", "Post")]
public async Task<IActionResult> IsEmailInUse(string email)
{
var user = await userManager.FindByEmailAsync(email);
if(user == null) { return Json(true); }
else { return Json($"Email {email} is already in use"); }
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
// Copy data from RegisterViewModel to IdentityUser
var user = new IdentityUser
{
UserName = model.Email,
Email = model.Email
};
// Store user data in AspNetUsers database table
var result = await userManager.CreateAsync(user, model.Password);
// If user is successfully created, sign-in the user using
// SignInManager and redirect to index action of HomeController
if (result.Succeeded)
{
await signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction("index", "home");
}
// If there are any errors, add them to the ModelState object
// which will be displayed by the validation summary tag helper
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
return View(model);
}
[HttpPost]
public async Task<IActionResult> Logout()
{
await signInManager.SignOutAsync();
return RedirectToAction("index", "home");
}
[HttpGet]
public IActionResult Login()
{
return View();
}
// Redirect Vulnerability Fix
[HttpPost]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var result = await signInManager.PasswordSignInAsync(
model.Email, model.Password, model.RememberMe, false);
if (result.Succeeded)
{
if(!string.IsNullOrEmpty(returnUrl))
{
return LocalRedirect(returnUrl);
}
return RedirectToAction("index", "home");
}
ModelState.AddModelError(string.Empty, "Invalid Login Attempt");
}
return View(model);
}
}
}
This Is My Startup.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using july_15_auth.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace july_15_auth
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
services.AddTransient<IEmployeeRepository, MockEmployeeRepository>();
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<AppDbContext>();
services.Configure<IdentityOptions>(options =>
{
options.Password.RequiredLength = 7;
options.Password.RequiredUniqueChars = 2;
options.Password.RequireNonAlphanumeric = false;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
'''
Upvotes: 2
Views: 288
Reputation: 27793
InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' while attempting to activate 'july_15_auth.Controllers.AccountController'
To fix above exception, please try to replace RoleManager<IdentityUser>
with RoleManager<IdentityRole>
while you inject an instance of RoleManager in your controller.
private readonly UserManager<IdentityUser> userManager;
private readonly SignInManager<IdentityUser> signInManager;
private readonly RoleManager<IdentityRole> roleManager;
public AccountController(UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager, RoleManager<IdentityRole> roleManager)
{
this.userManager = userManager;
this.signInManager = signInManager;
this.roleManager = roleManager;
}
For more information about RoleManager<TRole>
, please check: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.rolemanager-1?view=aspnetcore-3.1
Upvotes: 2