I have a .Net application that uses an arbitrary number of Membership providers. I will not go into the reasons, but I do not want these to be pre-configured, but I want to create and add them programmatically. Is there anyway to do this? I have no problem creating the providers, but Membership.Providers is readonly, so I can't add them.
An easy hack is to create a custom membership provider (as wrapper) first and hook it in web.config. Then you implement this provider to be able to authenticate users against a list of real membership providers.
As the wrapper is owned by you, you are only limited by your imagination.
Late, late answer, but you can use reflection:
public static class ProviderUtil
{
static private FieldInfo providerCollectionReadOnlyField;
static ProviderUtil()
{
Type t = typeof(ProviderCollection);
providerCollectionReadOnlyField = t.GetField("_ReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
}
static public void AddTo(this ProviderBase provider, ProviderCollection pc)
{
bool prevValue = (bool)providerCollectionReadOnlyField.GetValue(pc);
if (prevValue)
providerCollectionReadOnlyField.SetValue(pc, false);
pc.Add(provider);
if (prevValue)
providerCollectionReadOnlyField.SetValue(pc, true);
}
}
Then, in your code, you can do something like this:
MyMembershipProvider provider = new MyMembershipProvider();
NameValueCollection config = new NameValueCollection();
// Configure your provider here. For example,
config["username"] = "myUsername";
config["password"] = "myPassword";
provider.Initialize("MyProvider", config);
// Add your provider to the membership provider list
provider.AddTo(Membership.Providers);
It's a hack, because we're using reflection to set the "_ReadOnly" private field, but it seems to work.
Here's a great post about this issue: http://elegantcode.com/2008/04/17/testing-a-membership-provider/
Another good post: http://www.endswithsaurus.com/2010/03/inserting-membershipprovider-into.html
Pay special attention to the warnings of using _ReadOnly in those posts, as you'll want to weigh the downsides of manipulating a readonly collection vs. your project requirements and what you're trying to accomplish.
Regards,
-Doug