Skip to content

Instantly share code, notes, and snippets.

@danielok
Created February 28, 2014 14:07
Show Gist options
  • Save danielok/9271691 to your computer and use it in GitHub Desktop.
Save danielok/9271691 to your computer and use it in GitHub Desktop.
Configuring AutoFac with ASP.NET MVC 5 Identity UserManager, ApplicationUser, UserStore
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterAssemblyTypes(typeof(MvcApplication).Assembly)
.AsImplementedInterfaces();
builder.RegisterModule(new AutofacWebTypesModule());
builder.RegisterType<ApplicationDbContext>().InstancePerHttpRequest();
builder.RegisterType<UserStore<ApplicationUser>>().As<IUserStore<ApplicationUser>>();
builder.RegisterType<UserManager<ApplicationUser>>();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
@EricLesch
Copy link

Thank you for this. It was helpful.

@priyanperera
Copy link

Thanks for your code. I tried using it but I get the following exception.
The entity type ApplicationUser is not part of the model for the current context.

My code is exactly the same except for this line.
builder.RegisterType<UserManager>();
I use the built in ApplicationUserManager class.
builder.RegisterType();

@Zowiks
Copy link

Zowiks commented Mar 16, 2015

Same problem as priyanparera...

@Thwaitesy
Copy link

@Zowiks @priyanperera

You need to make sure the UserStore uses your ApplicationDbContext and not the generic DbContext. To do this with with Autofac you can create a resolved parameter like the the one below:

   var dbContextParameter = new ResolvedParameter((pi, ctx) => pi.ParameterType == typeof(DbContext),
                                                           (pi, ctx) => ctx.Resolve<ApplicationDbContext>());

   builder.RegisterType<UserStore<ApplicationUser>>().As<IUserStore<ApplicationUser>>().WithParameter(dbContextParameter).InstancePerLifetimeScope();

@dnistreanu
Copy link

dnistreanu commented May 9, 2018

I get the same error as @priyanperera and @Thwaitesy solution doesn't work, it says that ApplicationDbContext is not registered, with the same code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment