Register IAuthenticationManager with Unity
Solution 1:
Here is what I did to make Unity play nice with ASP.NET Identity 2.0:
I added the following to the RegisterTypes
method in the UnityConfig
class:
container.RegisterType<DbContext, ApplicationDbContext>(
new HierarchicalLifetimeManager());
container.RegisterType<UserManager<ApplicationUser>>(
new HierarchicalLifetimeManager());
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(
new HierarchicalLifetimeManager());
container.RegisterType<AccountController>(
new InjectionConstructor());
Solution 2:
Try adding below line in the class UnityConfig
:
container.RegisterType<IAuthenticationManager>(
new InjectionFactory(
o => System.Web.HttpContext.Current.GetOwinContext().Authentication
)
);
Solution 3:
If you really want to use Unity to manage all your dependencies, you could try to register also the IAuthenticationManager in Unity
container.RegisterType<IAuthenticationManager>(
new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
With some small adaptations, you can then use Unity to resolve all needed dependencies for Asp.net Identity.
I found a great post on this (also tested by me) here:
http://tech.trailmax.info/2014/09/aspnet-identity-and-ioc-container-registration/
Solution 4:
This will also work as a complete configuration to allow the use of Unity with Identity 2.0:
container.RegisterType<MyDbContext>(new PerRequestLifetimeManager(), new InjectionConstructor());
// Identity
container.RegisterType<UserManager<User>>(new HierarchicalLifetimeManager());
container.RegisterType<SignInManager<User, string>>(new HierarchicalLifetimeManager());
container.RegisterType<IUserStore<User>, UserStore<User>>(new PerRequestLifetimeManager(), new InjectionFactory(x => new UserStore<User>(GetConfiguredContainer().Resolve<MyDbContext>())));
container.RegisterType<IAuthenticationManager>(new InjectionFactory(x => HttpContext.Current.GetOwinContext().Authentication));
With this setting, you won't need to register the AccountController or ManageController types with Unity.