This is a real cool facility that I just used in my Hybrid CMS. There is a full in depth walkthrough on BitterCoder’s Blog here but I will describe how I used it in this blog post.
I needed to be able to have the kernel instantiate a specific implementation of IAuthService. This Interface has a couple of method definitions, but most important it had the Authenticate() method. The idea behind this is that I can swap out IAuthService and change the way a user is authenticated. At the moment Active Directory and Database is supported.
So in the whole architecture I have the following classes/interfaces
- IAuthService
- DbAuthService : IAuthService (component id: db.authService)
- AdAuthService : IAuthService (component id: ad.authService)
In the Castle config section for Windsor, they have the following component Id’s listed above. Both of these component declarations have factory=authServiceFactory which activation of the components are deferred to at runtime.
In the AppSettings section I have an Application Setting called authStore=db.authService, which just has whichever component will be used for authentication.
Here is the code for AuthServiceFactory to give you an idea how the AuthService’s are returned from the kernel:
public class AuthServiceFactory : IAuthServiceFactory {</pre> private IKernel _kernel;public AuthServiceFactory(IKernel kernel) { _kernel = kernel; } protected string AuthStoreType { get { return ConfigurationManager.AppSettings["authStoreType"]; } } public IAuthService Create() { return (IAuthService)_kernel.Resolve(AuthStoreType, typeof(IAuthService)); } }
Pretty cool huh? Now if I want to introduce a new method of Authentication I only need to add the component to the config file, make an implementation and select it in the AppSetting. Very flexible! =)