Switching between ASP.NET application services providers at runtime.

by Scosby Wednesday, April 15, 2009

I had to spend a little time thinking about this one tonight, so here it is for you to digest!

Let's say you have a web app that utilizes the ASP.NET Role provider and Membership provider. Specifically, we'll focus on the SQL providers (SqlRoleProvider and SqlMembershipProvider). It is easy enough to wire these providers up in your web.config and get things running quickly (yay for agility *cough*). Visit either link for the SQL provider classes mentioned above for a sample web.config from MSDN if you're still wondering.

Consider the following: what if I want to set up "test" or "staging" environment providers in the web.config and have the web app use the "test" provider instead of the default (production) provider during testing? In my case, I wanted to use different databases, but this could easily happen to you should you wish to use a completely different provider depending on a condition (for instance, a query string parameter might indicate you should use an Active Directory or Oracle provider, ect).

At first, I thought I could simply change the application's provider at runtime but it became obvious to me, eventually ;), that it wasn't going to work. Instead, I created a static ProviderManager class which returns a cached instance of a Role or Membership provider. It was a pity to say goodbye to the Roles and Membership classes, but alas, I now delegate them to my ProviderManager class' method when I want to work with either provider. This ProviderManager class makes it possible for me to cache the desired provider from the web.config based on any criteria of my choosing. In my case, I simply choose to use the DEBUG constant with compiler directives to return my "test" or "staging" providers (only when debugging, obviously). You certainly could make it more complicated and work with any number of conditions, such as multiple connection strings and/or providers. Enjoy!

public static class ProviderManager
{
     private static MembershipProvider membershipProvider;

       .....

     public static MembershipProvider GetMembershipProvider()
     {
          if (ProviderManager.membershipProvider == null)
          {
               //Get the default provider
               MembershipProvider provider = Membership.Providers["ScosbyMembershipProvider"];
#if DEBUG
          provider = Membership.Providers["TestMembershipProvider"];
#endif
               ProviderManager.membershipProvider = provider;
          } 
               return ProviderManager.membershipProvider;
     }

      ..... 

}

Thus, instead of writing code such as: Roles.CreateRole("WidgetTechs");

We write code to use the new ProviderManager class: ProviderManager.GetRoleProvider().CreateRole("WidgetTechs");

Tags: ,

Technology | Programming

blog comments powered by Disqus