Search code examples
c#asp.netmembership

Using Membership rather than just creating your own class


I'm starting to use the 'Membership' framework (as you may have noticed from my past 5 posts).

In my code I'm inheriting the SqlMembershipProvider class and overriding the functions, because my database doesn't fit the schema required by default.

So the question I wish to ask is:

Why should I use the Membership class, when I can just create my own class with the functions that I wish to use within my application?

The same goes for the Roles framework too.


Solution

  • First of all, if you have your own preexisitng user database you should probabaly not try to coerce the SqlMembershipProvider to use it. SqlMembershipProvider is a complete implementation of the abstract MembershipProvider class and to function correctly it requires a database with the correct schema.

    Instead you should create your own implementation of the abstract MemberShipProvider class. To get started, create a class CoultonsMemebshipProvider and have it derive from System.Web.Security.MembershipProvider. Then put the cursor inside MembershipProvider and click Ctrl+. and then select Implement abstract class.... Visual Studio will then add in a lot of code for methods you can implement.

    At first after seeing the VS inserted code, the task looks daunting indeed. But remember that you only have to actually implement the parts that your application is going to need. It's OK to leave the default throw new NotImplementedException(); in place for methods and properties you are not going to need.

    Now for you question "Why should I use the Membership class...", the answer is simple enough. It's a tried and tested, well thought out abstraction which guides you in the correct direction when building you authentication scheme.

    That said, if you strongly feel that you don't actually need a membership provider, you can still use FormsAuthentication and get the benefits it provides. If you want to explore this option, have a look at this tutorial on FormsAuthentication by Scott Mitchell (specifically the Introduction part).