Search code examples
c#.netasp.net-coreasp.net-identityidentityserver4

Get all roles in asp.net core identity using a separate class


I've been trying to get a list of all the roles out of asp.net core identity, This is how I've done t before using a controller:

public AdminController(
        UserManager<ApplicationUser> userManager,
        ILogger<AccountController> logger,
        IEmailSender emailSender,
        RoleManager<IdentityRole> roleManager,
        SignInManager<ApplicationUser> signInManager)
    {
        _userManager = userManager;
        _logger = logger;
        _emailSender = emailSender;
        _roleManager = roleManager;
        _signInManager = signInManager;
    }

private void PuplateRolesList(RegisterViewModel model)
    {
        model.Roles = _roleManager.Roles?.ToList();
    }

What I'm trying to do is have a class I can re-use that will pass back a list of all the roles and not use controller I tries this:

var roleStore = new RoleStore<AppRole, int, AppUserRole>(dbContext);
var roleMngr = new RoleManager<AppRole, int>(roleStore);

But in a class it obviously doesn't construct the role manager or dbContect, so i tried it myself but it doesn't work. Any ideas how I can have a class in my app deliver a list or roles so I don't have it all in my controller?

Thanks


Solution

  • Create a class:

    public class RoleUtility 
    {
        private readonly RoleManager<IdentityRole> _roleManager;
    
        public RoleUtility(RoleManager<IdentityRole> roleManager)
        {
            _roleManager = roleManager;
        }
    
        public void PopulateRolesList(RegisterViewModel model)
        {
            model.Roles = _roleManager.Roles?.ToList();
        }
    }
    

    Extract the interface:

    public interface IRoleUtility
    {
        void PopulateRolesList(RegisterViewModel model);
    }
    

    The RoleUtility class declaration become:

    public class RoleUtility: IRoleUtility
    

    Then, in your Startup class :

    public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddTransient<IRoleUtility, RoleUtility>();
    }
    

    Your controller code become:

    public AdminController(
            UserManager<ApplicationUser> userManager,
            ILogger<AccountController> logger,
            IEmailSender emailSender,
            IRoleUtility roleUtility,
            SignInManager<ApplicationUser> signInManager)
        {
            _userManager = userManager;
            _logger = logger;
            _emailSender = emailSender;
            _roleUtility = roleUtility;
            _signInManager = signInManager;
        }
    
    private void PuplateRolesList(RegisterViewModel model)
        {
            _roleUtility.PopulateRolesList(model);
        }