If you are familiar with ASP.NET 2.0, you understand the
concept of providers. Built-in to this version of the framework are the
Membership, Roles, and Profile providers, to name a few. In trying to
understand providers are on my own, they turned out to be very complex
mechanisms, involving so many different types of parts. So, I wanted
to write this article to show you the concept of creating your own custom
provider from scratch. In order to understand how it all works, you have
to understand that with each provider, there are four parts:
·
Abstract class that defines the required properties/methods, and
the derived implementations that provide the specific functionality
·
Configuration section that sets up the provider for your .NET
application
·
Static class that makes the provider accessible to all
Using the membership provider as an example, you will see
that this provider incorporates a membership element that resides as a
child of the system.web parent element. The MembershipProvider
abstract class is defined in the System.Web.Security namespace, where all
existing and any new providers inherit from. To make use of this
provider, the static Membership class ties in the derived provider types and
utilizes the configuration section to set up the providers in the collection,
as you will see. To the user interface, the static class exposes the
properties and methods of the default provider, which is specified in the
configuration file. In this way, it is a decoupled approach, as the
Membership static class needs to know nothing about your implementation of the
abstract class, and comes to find out which provider to use through the
configuration file at runtime.
However, specific implementations of the provider approach
are coupled in itself; the SqlMembershipProvider class requires the ASPNET
standard database that is created by default for new web applications in Visual
Studio .NET. You can also specify a custom SQL database, but the table/stored
procedure structure must be the same, which is where the rigidity comes into
play. However, it is possible to create a less-coupled approach based on
the design of the provider. For instance, a provider could implement the base
MembershipProvider class and expose the names of the tables or stored
procedures, so the developer can use a custom structure of sorts. There are
many possibilities.
Getting back to our custom provider example, the example I
will be using is a Newsletter provider, which allows users to subscribe to
certain newsletters belonging to a specific application. An administrator
will setup the newsletters that will be provided through the site, as well
as other subscriber/newsletter administrative features. You will see and
understand the code in a moment. Let's start at the beginning: the
abstract class.