I'm in the middle of a redesign on the part of my current project that deals with user permissions and authorization. I have an interface named IUserPermissions
that encapsulates this information.
One part of a user's permissions are the Roles which they are a member of. I'm trying not to violate the Open/Closed Principle by adding every possible role to IUserPermissions
as a property like this:
interface IUserPermissions {
bool IsAdmin { get; set; }
bool IsDeveloper { get; set; }
// Many more...Yuck.
}
I feel that having an interface like this would suit the OCP better:
interface IUserPermissions {
ICollection<IRole> Roles { get; }
bool IsInRole<T>() where T : IRole; /* (For convenience; Would probably be
implemented as an extension method) */
}
interface IRole {
string Name { get; }
}
public class AdminRole : IRole {
public string Name { get { return "Admin"; } }
}
Where I'm falling down is how to implement something like this. I'm using the ASP.NET Roles API as the backing store, meaning I'll be given a string[]
of role names for the user. My IUserPermissions
implementation would have to start with this collection of strings and somehow work backwards, then instantiate a bunch of appropriate IRole
s to populate the Roles
property.
This could be done by scanning the assembly for IRoles
with a parameterless constructor, instantiating them, and reading their Name
property, but...ugh. How can I fix this design so that I don't have to do this?
Roles
auto-register themselves on startup, but apparently that's not feasible in C#. Feel free to take a look at my question trying to figure out how to do it, and you can see my sample code I was going to include in the answer and the answer I got for how to actually make it work.