Cannot figure out why Unity is not injecting Ident

2019-08-09 13:49发布

问题:

I am new to Unity, and Identity, and I have restructured my implementation of Identity 2 to use int Keys instead of strings. I followed this article. It works great at this point. However, I am using Unity for IoC, and it works wonderfully with my repositories, however, I am struggling getting it to work with the Identity side. I followed this article to switch.

I have seen questions similar to this, but all of them were using string Keys, so I assume I have something funky somewhere since I am using int.

The issue is in the ctor of the ApplicationUserStore class:

public class ApplicationUserStore :
    UserStore<ApplicationUser, ApplicationRole, int,
    ApplicationUserLogin, ApplicationUserRole,
    ApplicationUserClaim>, IUserStore<ApplicationUser, int>,
    IDisposable
{
    public ApplicationUserStore(IdentityDb context)
        : base(context)
    {
    }
}

Here is the IdentityDb.cs:

public class IdentityDb : IdentityDbContext<ApplicationUser, ApplicationRole, int,
    ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
    public IdentityDb()
        : base("DefaultConnection")
    {
    }

    static IdentityDb()
    {
        // Set the database initializer which is run once during application start
        // This seeds the database with admin user credentials and admin role
        Database.SetInitializer<IdentityDb>(new IdentityDbInitializer()); 
    }

    public static IdentityDb Create()
    {
        return new IdentityDb();
    }
}

And here is the relevant portion of UnityConfig.cs:

container.RegisterType<IdentityDb>(new PerResolveLifetimeManager());
container.RegisterType<ApplicationSignInManager>();
container.RegisterType<ApplicationUserManager>();
container.RegisterType<ApplicationRoleManager>();
container.RegisterType<IAuthenticationManager>(
     new InjectionFactory(c=>HttpContext.Current.GetOwinContext().Authentication));
container.RegisterType<IUserStore<ApplicationUser, int>, ApplicationUserStore>(
     new InjectionConstructor(typeof(IdentityDb)));

When I attempt to run the app, the context parameter in the ctor of ApplicationUserStore is null.

I would appreciate any help that could be offered.

Thank you!

回答1:

You have an exception while resolving UserManager. But MVC's Dependency resolver swallows it and return null instead of object.

In the Startup.Auth.cs instead of

app.CreatePerOwinContext(() => 
     DependencyResolver.Current.GetService<ApplicationUserManager>()); 

write:

app.CreatePerOwinContext(() => 
     UnityConfig.GetConfiguredContainer().Resolve<ApplicationUserManager>());
//Don't forget to add Microsoft.Practices.Unity namespace

This cause your program fails when Unity could not resolve object and throws an exception. By reading details of the exception you could find the issue. If you need future help simply submit the exception too.