开发者

Login Model for ASP.NET

can you help me with my problem:

i have ASP.NET web site that have some basic authorization features (Login/Logoout e.t.c.). Currently i have 3 main methods:

  • bool Login(string name, string password);
  • bool IsLogged();
  • string GetUserID();

All this methods are "hardcoded" into one class. Login methods checks database to determine that user exists. But then I've decided to use XML file to store users, it means that all logic that checked a user should be rewritten.

I've got an idea to use the following "pattern":

  1. Create interface (e.g. ILoginProvider) that declares those 3 methods that described above
  2. Implement this interface in any class and write specific logic in Login() method to check XML file or database
  3. Pass this class to ??? (here is my problem)

I thought to make a class (e.g. LoginHelper) that can take ILoginProvider interface as an argument:

class LoginHelper {

    private static ILoginProvider provider;

    // this method should be called somewhere in Application_Startup event in Global.asax
    public static void RegisterLoginProvider(ILoginProvider inst) {
        provider = inst; 
    }
}

and then write necessary methods:

public static bool IsLogged() {
   开发者_如何学Python return provider.IsLogged();
}

and then call RegisterLoginProvider() method in Global.asax in Application_Startup event:

MyCustomProvider prov = new MyCustomProvider(); // this class implements ILoginProvider interface
LoginHelper.RegisterSecurityProvider(prov);

Is it a correct way to implement such logic to change some "providers" with others?


The way this is often done is via a service locator (Unity, StructureMap etc) or a custom factory where you ask for an instance of ILoginProvider and the correct one is returned.

The responsibility of selecting which kind of ILoginProvider to create is not up to the calling class.

//get a login provider from via a service locator
ILoginProvider provider = DependencyLookup.Resolve<ILoginProvider>();

With the service locators, you would register against ILoginProvider which implementation to use, either in XML configuration or in code. Here is an example for Unity.

public static class ContainerConfiguration
{
    public static void Configure()
    {
        ServiceLocator.Current.RegisterType<ILoginProvider, XmlLoginProvider>();
    }
}


You have tried to abstract out the login functionalities which is very nice. Further you have to make this helper to page binding through DependencyInjecttion i.e you have to add a constrcutro to the class with LoginInterface as the argument. Then you can use utilities like StructureMap to get the instances at runtime.

By means of having the interfaces we can provide adaptability for future cases where you can move to DB or webservice.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜