I'm using Unity successfully for all regular constructor injection such as repositories etc., but I can't get it working with the ASP.NET Identity classes. The setup is this:
public class AccountController : ApiController
{
private UserManager<ApplicationUser> _userManager { get; set; }
public AccountController(UserManager<ApplicationUser> userManager)
{
if (userManager == null) { throw new ArgumentNullException("userManager"); }
_userManager = userManager;
}
// ...
}
with these configs for Unity:
unity.RegisterType<AccountController>();
unity.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
unity.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());
That's the same as other posts here for Autofac, Ninject e.g., but it doesn't work in my case. The error message is:
An error occurred when trying to create a controller of type 'AccountController'. Make sure that the controller has a parameterless public constructor.
Manual creation works of course:
public AccountController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>("Mongo")))
{
}
What's wrong?
UPDATE
As suggested by @emodendroket, shortening the code to this does the trick. No need for the Unity.Mvc package.
unity.RegisterType<IUserStore<IdentityUser>,
MyCustomUserStore>(new HierarchicalLifetimeManager());
and
public AccountController(UserManager<IdentityUser> _userManager,
IAccountRepository _account)
{
// ...
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…