Created
February 28, 2014 14:07
-
-
Save danielok/9271691 to your computer and use it in GitHub Desktop.
Configuring AutoFac with ASP.NET MVC 5 Identity UserManager, ApplicationUser, UserStore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); |
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();
Same problem as priyanparera
...
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();
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
Thank you for this. It was helpful.