Ninject with asp.net identity

时间:2017-04-06 17:17:31

标签: c# asp.net asp.net-identity ninject

I'm trying to use ninject with asp.net identity and currently I was doing the following for the bindings:

kernel.Bind(typeof(IUserStore<>)).To(typeof(UserStore<>));

Here you have the classes definitions:

public interface IUser : IUser<string>

public interface IUserStore<TUser> : IUserStore<TUser, string>, IDisposable where TUser : class, IUser<string>

public class IdentityUser : IdentityUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUser, IUser<string>, IGenerateKeys

public class UserStore<TUser> : UserStore<TUser, IdentityRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUserStore<TUser>, IUserStore<TUser, string> where TUser : IdentityUser, new()

public class Context {
    public Context(ILogger Logger, Dictionary<string, string> LocalConfig, IUserStore<IUser> UserManager
         ){...}
}

When I try to do kernel.Get<Context>() I get the error about not being able to cast IUserStore to UserStore.

Unable to cast object of type 'UserStore`1[IdentityUser]' to type 'Microsoft.AspNet.Identity.IUserStore`1[Microsoft.AspNet.Identity.IUser]'.

I don't really understand why this is not working but in fact trying the following IUserStore<IdentityUser> dummy = new Store<IdentityUser>() gives no compilation error, but this IUserStore<IUser> dummy = new Store<IdentityUser>() does, but i can't understande why since IdentityUser implements IUser.

Anyone had any similar problem?

1 个答案:

答案 0 :(得分:1)

如果查看 Microsoft.AspNet.Identity.EntityFramework ,您可以看到UserStore中的TUser必须是IdentityUser的类型而不是IUser,这就是编译错误的原因。

public namespace Microsoft.AspNet.Identity.EntityFramework
{
//
// Summary:
//     EntityFramework based user store implementation that supports IUserStore, IUserLoginStore,
//     IUserClaimStore and IUserRoleStore
//
// Type parameters:
//   TUser:
public class UserStore<TUser> : UserStore<TUser, IdentityRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUserStore<TUser>, IUserStore<TUser, string>, IDisposable where TUser : IdentityUser
{
    //
    // Summary:
    //     Default constuctor which uses a new instance of a default EntityyDbContext
    public UserStore();
    //
    // Summary:
    //     Constructor
    //
    // Parameters:
    //   context:
    public UserStore(DbContext context);
   }
}

您应该始终使用IdentityUser,因为IUser只是IdentityUser的最小接口。

如果您想将Ninject与Identity一起使用,那将会非常棘手,您可以在此处找到分步解决方案:How to inject User Manager to Account Controller with default Identity Model in Identity 2 using Ninject