CleanArchitecture icon indicating copy to clipboard operation
CleanArchitecture copied to clipboard

Create Role

Open asgharb opened this issue 7 months ago • 0 comments

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<IdentityRole> _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?

asgharb avatar Mar 17 '25 07:03 asgharb