Reputation: 195
This just happened to me a while ago. In my code, I need to get the Roles
that a specified user in assigned in.
here is what's in my code:
string[] roles = {};
SqlRoleProvider fxSRP = new SqlRoleProvider();
string id = Request.QueryString["UserName"] as string;
string userName = id;
now this is all fine, but when I get to this bit:
roles = fxSRP.GetRolesForUser(userName);
The system throws that godforsaken Object reference not set to an instance of an object
exception. Has driven me nuts for a few minutes, honestly. but, when I change that small bit of code to this (this is an explicit call, right?) :
roles = Roles.GetRolesForUser(userName);
The code works. I'm able to retrive the Roles
for the user and use them however I want.
I want to know, why is it that using the GetRolesForUser
from the instatiated SqlRoleProvider
doesn't work? Because this might also happen for the next bit of code that I will work on, which is to use RemoveUsersFromRoles
and AddUsersToRoles
. And also, what kind of instance is the program looking for? What have I not instantiated for the method to work?
Upvotes: 0
Views: 459
Reputation: 18965
Although @Chris Culter's suggestion would likely better serve as a comment as-is, there's a good chance that if the framework recommends not instantiating an object directly you probably shouldn't be. Doing so likely skips several significant initialization steps on the instantiated object which means you likely haven't provided it well enough for its expected use.
You stumbled across the recommended way of doing what you're after so why bother with the option that doesn't work (especially considering it's explicitly not recommended)?
If there's specifically something you gain from using this class in this way then I'd recommend pulling the relevant assembly's into ILSpy or Reflector and start digging around how your specific use case is used by the framework to ensure you're mimicing the behavior to a T.
Even still depending on unrecommended behavior, regardless of how public it may be, is highly discouraged as it is possible to change in the future without notification. Better to depend on how classes should be used rather than a niche compile requirement.
Upvotes: 1
Reputation: 4556
You're calling new SqlRoleProvider()
, but according to the documentation for that constructor, http://msdn.microsoft.com/en-us/library/system.web.security.sqlroleprovider.sqlroleprovider.aspx:
The SqlRoleProvider constructor is called by ASP.NET to create an instance of the SqlRoleProvider class as specified in the configuration for the application. This constructor is not intended to be used from your code.
(Emphasis mine.) I'm not an expert on this class, but I think this remark indicates that you shouldn't try to do that.
Upvotes: 1