Register IAuthenticationManager with Unity

北城余情 提交于 2019-11-27 18:18:31
user3849637

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());
abdulbasit

Try adding below line in the class UnityConfig:

container.RegisterType<IAuthenticationManager>(
    new InjectionFactory(
        o => System.Web.HttpContext.Current.GetOwinContext().Authentication
    )
);

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/

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.

Reputation won't let me comment, but to add to user3849637s marked answer, for MVC with Update 3, you will also need to add the ManageController as some functions use that with the updated scaffolding:

container.RegisterType<ManageController>(new InjectionConstructor()); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!