views:

249

answers:

1

I need to be able to set a RoleProvider at runtime. I don't even know where it is coming from -- I am using some loosely coupled dependency injection -- so I can't even define it in the web.config file.

How do I set the role provider at runtime?

+1  A: 

I would create a custom RoleProvider. This role provider is the only provider that needs to be registered in the web.config.

In the Initialize method you can load whichever provider you wanted to in code and store it as a private member of your custom provider.

From that point on your Role Provider is simply a proxy for your chosen provider. Example:

public class CustomRoleProvider : RoleProvider
{
    //The real role provider;
    private RoleProvider _provider;

    public CustomRoleProvider()
    { }

    public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
    {
        base.Initialize(name, config);
        //In here initalise your Role Provider at run time
        //This is just demo code... obviously you would do something a little more
        //intelligent
        SqlRoleProvider provider = new SqlRoleProvider();
        provider.Initialize("sql", config);
        _provider = provider;
    }

    public override void AddUsersToRoles(string[] usernames, string[] roleNames)
    {
        _provider.AddUsersToRoles(usernames, roleNames);
    }
    public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
    {
        return _provider.DeleteRole(roleName, thrownOnPopulatedRole);
    }
    //other proxy methods would also be here...
}

You could see how you might expand this to support multiple providers and choose at run time which of your providers you could use.

Does that answer your question?

Gavin Osborn
Yeah, it does... Kind of That is actually what I was doing already... but I wasn't keen on this type of proxy. Deriving AND composing one's self of the same type can lead to troubles... and is ugly. BUT, it is the only thing I can come up with so far, so +1.
Brian Genisio