Pages

Friday, October 24, 2008

Provider Model (ASP.NET)

Provider model is just a way to allow user to contribute to API. For example you have a API with Class SecurityProvider:
public abstract class BaseSecurityProvider
{
    public bool Authenticate(string userName, string password);
}


Then you have defined an Sql2005SecurityProvider derived from BaseSecurityProvider as follows:
public class Sql2005SecurityProvider : BaseSecurityProvider
{
   public override bool Authenticate(string userName, string password)
    {
         //add logic here to authenticate against sql server 2005
     }
}


You have exposed your API with those Sql2005SecurityProvider so that user can authenticate against Sql server 2005. Now what if user wants to use Oracle or Active directory? May be one solution would be to implement another security provider such as OracleSecurityProvider. But it would be easier if we allow users to implement their own provider. To do so provider model is a best choice. To implement the provider model we need to refractor the BaseSecurityProvider abstract class. The modified code should look like as below:
    public abstract class BaseSecurityProvider
    {
        public bool Authenticate(string userName, string password);
        public static BaseSecurityProvider GetInstance()
        {
            string typeName = ConfigurationManager.AppSettings["TypeName"];
            string assemblyName = ConfigurationManger.AppSettings["AssemblyName"];
            BaseSecurityProvider securityProvider = System.Activator.CreateInstance(assemblyName, typeName);
        }
    }


Now users can implement a ActiveDirectory security provider class derived form BaseSecurityProvider and write necessary code in Authenticate method to authenticate against Active Directory:
public class ActiveDirectorySecurityProvider : BaseSecurityProvider
{
   public override bool Autheticate(stirng userName, string password)
   {
         //authenticate against AD.
    }
}

and then user can add the two entries in config file as
<AppSettings>
   <add key="AssemblyName" value................./>
   <add key="TypeName" value="ActiveDirectorySecurityProvider" />
</AppSettings>

Now to use your Active directory provider the code block will be
if (ActiveDirectorySecurityProvider .GetInstance().Authenticate(userName, password))
{
// authenticattion succeed
}

Now if a company say (Jaxara IT) supply the API with two class BaseSecurity provider and Sql2005SecurityProvider then another programmer of another company (say Orion Informatics Ltd.) can write a class inherited form BaseSecurityProvider to authenticate against another source.

For more information you can read Scott Mitchell's post here

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.