简体   繁体   中英

Use AspNetCore.Identity RoleManager and UserManager in an Interface

I'm implementing RoleManager and UserManager in an Interface, I'm aware of some of the potential benefits, like Unit Testing, is there any drawbacks of doing this?

AdministrationDataService.cs:

public class AdministrationDataService : IAdministrationDataService
  {
    private readonly RoleManager<IdentityRole> _roleManager;

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

    public IQueryable<IdentityRole> GetRolesList()
    {
      var roles = _roleManager.Roles;

      return roles;
    }
  }

IAdministrationDataService.cs:

public interface IAdministrationDataService
  {
    IQueryable<IdentityRole> GetRolesList();
  }

Then I'm using it like this.

ViewRoles.cshtml.cs:

public class ViewRolesModel : PageModel
  {
    public List<IdentityRole> Roles { get; set; } = new List<IdentityRole>();

    private readonly IAdministrationDataService _administrationDataService;

    public ViewRolesModel(IAdministrationDataService administrationDataService)
    {
      _administrationDataService = administrationDataService;
    }

    public void OnGet()
    {
      Roles = _administrationDataService.GetRolesList().ToList();
    }
  }

Which other benefit do I get by using this approach instead of just using RoleManager in ViewRoles.cshtml.cs

What you described above can be concluded as dividing the getting roles method into 2 independent method: IAdministrationDataService.GetRolesList() and _roleManager.Roles .

The drawbacks can be recognized as requiring more configurations and may lead to a complex business logic in your project which requires more comment to explain the method. But the advantages is obviously. In the future, if your business logic changed or expanded, you no need to re-construction your structure as you've set 2 interfaces for the getting roles method, IAdministrationDataService works like an entrance and it will always the same for the view, therefore any backend changing won't influence your frontend.

Just like, app.UseRouting() and app.UseEndpoints() , splitting means decoupling control, and it will make your project flexible, easy to expand, but all these benefits will appear only when your project will expand to a complex, large, full of business logic project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM