Home > Back-end >  UserManager class is null even with dependency injection
UserManager class is null even with dependency injection

Time:10-13

I am working on an ASP.NET Core MVC application that uses ASP.NET Core identity for role based authorization and I'm facing an issue trying to figure out how to work with the UserManager class. The app should work as follows:

  1. A coach logs in to the web app through Identity to work with runner's data (e.g., taking attendance, starting a practice, etc.).

  2. The app should use the UserManager class to loop through all identity objects (registered users) so that the coach can manipulate user's data that have the role of Runner (there are currently 4 roles in the database and I am trying to use the UserManager class to only to select a specific role [Runner]) and then add the objects to a list for manipulation.

The problem that I am facing is that the UserManager object that I have created is null and after countless hours of googling, I'm not sure how to fix my problem.

On my first attempt, I received a null error and after a bit of research, I attempted to fix the error through dependency injection. The second error I received is "Unable to resolve service type while attempting to activate". I have tried configuring the service an I am currently at a standstill. How exactly do I configure the service? Here is the Controller class in question and also the Program.CS class in question. I've also added two images that can hopefully explain my problem more.

Controller:

[Authorize(Roles = "Master Admin, Coach")]
[Area("Coach")]
public class TakeAttendanceController : Controller
{ 
    private readonly IUnitOfWork _unitOfWork;
    private readonly UserManager<ApplicationUser> _userManager; // the UserManager object in question
    public TakeAttendanceController(IUnitOfWork unitOfWork, UserManager<ApplicationUser> userManager)
    {
        _unitOfWork = unitOfWork; 
        _userManager = userManager;
    }

    public IActionResult RecordAttendance()
    {
        var recordAttendanceViewModel = new RecordAttendanceViewModel();

        var userClaimsIdentity = (ClaimsIdentity)User.Identity;
        var userClaim = userClaimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
        if (userClaim != null)
        {
            recordAttendanceViewModel.UserCoach = _unitOfWork.ApplicationUser.GetById(userClaim.Value);
        }

        var users = _userManager.GetUsersInRoleAsync("Runner"); // object is null
        return View(recordAttendanceViewModel);
    }

    public IActionResult RecordWorkouts()
    {
        return View();
    }
}

Program.cs file:

using FinalMockIdentityXCountry.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using FinalMockIdentityXCountry.Models.DataLayer.Repositories.IRepository.Interfaces;
using FinalMockIdentityXCountry.Models.DataLayer.Repositories.IRepository.Classes;
using Microsoft.AspNetCore.Identity.UI.Services;
using FinalMockIdentityXCountry.Models.Utilities;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
var serverVersion = new MySqlServerVersion(new Version(8, 0, 30)); //current version of mysql - 8.0.30

builder.Services.AddDbContext<XCountryDbContext>(options => options.UseMySql(connectionString, serverVersion));

builder.Services.AddIdentity<IdentityUser, IdentityRole>()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<XCountryDbContext>();
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
builder.Services.AddSingleton<IEmailSender, FakeEmailSender>();
builder.Services.ConfigureApplicationCookie(options =>
{
options.LoginPath = $"/Identity/Account/Login"; 
options.LogoutPath = $"/Identity/Account/Logout";
options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
});
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.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseAuthentication();;

app.UseAuthorization();
app.MapRazorPages();
app.MapControllerRoute(
name: "default",
pattern: "{area=Welcome}/{controller=Home}/{action=Index}/{id?}");

app.Run();

The null error

Service error

CodePudding user response:

shouldnt builder.Services.AddIdentity<IdentityUser, IdentityRole>()

be

builder.Services.AddIdentity<ApplicationUser, IdentityRole>()

Or the injected service be

UserManager<IdentityUser>

  • Related