Configuring Microsoft.AspNet.Identity in Castle Windsor

It’s very easy to setup Microsoft.AspNet.Identity in the Castle Windsor container if you want to be able to inject UserManager and AuthenticationManager services:

container.Register(Component.For<UserManager>()
  .UsingFactoryMethod((kernel, creationContext) =>
  new UserManager(new UserStore(new ApplicationDbContext())))
  .LifestylePerWebRequest());

container.Register(Component.For()
  .UsingFactoryMethod((kernel, creationContext) =>
  HttpContext.Current.GetOwinContext().Authentication)
  .LifestylePerWebRequest());

The assumption here is your application is using a custom user class called ApplicationUser, which is the default setup by the MVC5 template.

There is one slight twist if you want to allow email addresses as user names:

container.Register(Component.For<UserManager>().UsingFactoryMethod((kernel, creationContext) =>
{
    var userManager = new UserManager(new UserStore(new ApplicationDbContext()));
    userManager.UserValidator = new UserValidator(userManager){AllowOnlyAlphanumericUserNames = false};
    return userManager;
}).LifestylePerWebRequest());

container.Register(Component.For()
  .UsingFactoryMethod((kernel, creationContext) =>
  HttpContext.Current.GetOwinContext().Authentication)
  .LifestylePerWebRequest());

Author: Tom Cabanski

Software Developer and Entrepreneur

%d bloggers like this: