我正在使用新的ASP.NET MVC 5 Identity框架进行身份验证。我传统上使用StructureMap进行依赖注入,但是我在使用新的AccountController进行连接时遇到了问题。
我的AccountController构造函数如下所示:
public AccountController()
: this(new UserManager<OmpUser>(new UserStore<OmpUser>(new OmpDbContext())))
{
}
public AccountController(UserManager<OmpUser> userManager)
{
UserManager = userManager;
}
我的StructureMap配置如下所示:
public static class IoC {
public static IContainer Initialize() {
ObjectFactory.Initialize(x =>
{
x.Scan(scan =>
{
scan.TheCallingAssembly();
scan.WithDefaultConventions();
});
//x.Register<IUserStore<OmpUser>>(() =>
// new UserStore<OmpUser>(new OmpDbContext()));
x.For<OMPEntities>().HttpContextScoped();
});
return ObjectFactory.Container;
}
}
当我运行项目时,我收到以下错误:
尝试获取类型实例时发生激活错误 AccountController,键“”
有关如何为建筑注入新建UserManager对象的任何想法?我试过四处寻找,但却找不到太多的指导。
答案 0 :(得分:27)
将以下代码添加到Container初始化方法中。
x.For<Microsoft.AspNet.Identity.IUserStore<ApplicationUser>>()
.Use<Microsoft.AspNet.Identity.EntityFramework.UserStore<ApplicationUser>>();
x.For<System.Data.Entity.DbContext>().Use(() => new ApplicationDbContext());
答案 1 :(得分:1)
添加[DefaultConstructor]属性将起作用。
public class AccountController : Controller
{
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
[DefaultConstructor] //This is the attribute you need to add on the constructor
public AccountController()
{
}
// Other implementations here..........
}
答案 2 :(得分:0)
@vikram,这对我有用。
cfg.For<IRoleStore<IdentityRole,string>>().Use<RoleStore<IdentityRole>>();