Skip to content

Create Role #1308

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
asgharb opened this issue Mar 17, 2025 · 0 comments
Open

Create Role #1308

asgharb opened this issue Mar 17, 2025 · 0 comments

Comments

@asgharb
Copy link

asgharb commented Mar 17, 2025

If I want to define a role and assign a role to a user, what is the procedure? In which layer should I define the interfaces and services?
this is my code in ((Application)):

`public class CreateRoleCommandHandler : IRequestHandler<CreateRoleCommand, bool>
{
private readonly IRoleService _roleService;

public CreateRoleCommandHandler(IRoleService roleService)
{
    _roleService = roleService;
}

public async Task<bool> Handle(CreateRoleCommand request, CancellationToken cancellationToken)
{
    var roleExists = await _roleService.RoleExistsAsync(request.RoleName);

    if (roleExists)
    {
        throw new InvalidOperationException($"Role '{request.RoleName}' already exists.");
    }

    var result = await _roleService.CreateRoleAsync(request.RoleName);

    if (!result)
    {
        throw new Exception($"Failed to create role '{request.RoleName}'.");
    }

    return true;
}

}`

and my code in((Infrastructure)):

`public class RoleService : IRoleService
{
private readonly RoleManager _roleManager;

public RoleService(RoleManager<IdentityRole> roleManager)
{
    _roleManager = roleManager;
}

public async Task<bool> RoleExistsAsync(string roleName)
{
    return await _roleManager.RoleExistsAsync(roleName);
}

public async Task<bool> CreateRoleAsync(string roleName)
{
    var result = await _roleManager.CreateAsync(new IdentityRole(roleName));
    return result.Succeeded;
}

}`

Is my path and method correct?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant