【发布时间】:2014-03-22 13:48:31
【问题描述】:
我成功地将 Unity 用于所有常规构造函数注入,例如存储库等,但我无法让它与 ASP.NET Identity 类一起使用。设置是这样的:
public class AccountController : ApiController
{
private UserManager<ApplicationUser> _userManager { get; set; }
public AccountController(UserManager<ApplicationUser> userManager)
{
if (userManager == null) { throw new ArgumentNullException("userManager"); }
_userManager = userManager;
}
// ...
}
使用 Unity 的这些配置:
unity.RegisterType<AccountController>();
unity.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
unity.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());
这与 Autofac 的其他帖子相同,例如 Ninject,但在我的情况下它不起作用。错误信息是:
尝试创建“AccountController”类型的控制器时出错。确保控制器有一个无参数的公共构造函数。 当然是手工创作作品:
public AccountController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>("Mongo")))
{
}
怎么了?
更新
正如@emodendroket 所建议的,将代码缩短到这个就可以了。不需要 Unity.Mvc 包。
unity.RegisterType<IUserStore<IdentityUser>,
MyCustomUserStore>(new HierarchicalLifetimeManager());
和
public AccountController(UserManager<IdentityUser> _userManager,
IAccountRepository _account)
{
// ...
【问题讨论】:
-
Mvc 和 web api 对 DI 使用不同的接口。 Nuget 来自 Microsoft P&P 的最新 Unity WebApi 包
-
确定吗?我只能看到“引导程序”包和 3rd 方库的差异,而不是 Unity 包本身。
-
你没有得到内部异常吗?
-
安装 Unity.Mvc 包。此外,您不需要注册控制器。该消息似乎表明您仍在使用默认控制器工厂,Unity.Mvc 应该提供帮助。
-
如果您刚刚安装了 Unity MVC 包并且在使用 ASP.NET 身份帐户控制器时遇到了问题,请参阅此处:stackoverflow.com/questions/20023065/…
标签: c# asp.net dependency-injection unity-container asp.net-identity