Recently I've answered a question on
StackOverflow
website and the question was how to create an overloaded method for both
AddToRoleAsync()
and
IsInRoleAync()
to look for the role by its ID and not by name. I this post I show how to extend
UserManager
class in the way it is implemented and access some internals of
UserManager
.
First way to extend the
UserManager
is using extension methods. In some cases you don't need to create another class to extend
UserManager
and by implementing some extensions methods to achieve what you want.
Before explaining why I cast the interface of _store to generic UserStore class with 9 parameters, let's look at the implementation AddToRoleAsync method (in such a case as good practice always check the source code of identity to get an idea to implement what you want)
Inside AddToRoleAsync implementation FindRoleAsync method is called and I checked FindRoleAsync implementation:
Inside FindRoleAsyncRole property is used to fetch a role by name and again I check Role definition:
I noticed I cannot use the Role property to the get role by identifier because it's private property but I noticed there is a public property of DbContext that I can use. So that's why I cast IUserStor interface to UserStore class to have access to Context property.
It's time to implement AddToRoleAsync() and IsInRoleAync():
It’s part of default implementation of UserStore class and it checks whether the current instance is disposed or not. github.com/dotnet/aspnetcore/blob/...
Built on Forem — the open source software that powers DEV and other inclusive communities.