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”:
- Create interface (e.g. ILoginProvider) that declares those 3 methods that described above
- Implement this interface in any class and write specific logic in Login() method to check XML file or database
- 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() {
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.
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.