Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i create an instance of UserManager

I am trying to learn how the new asp.net identity 2.0 works, but with little documentation I am hitting quite a few stumbling blocks.

I have this code below based off of a couple of tutorials that I have read:

public class CustomRole : IdentityRole<string, CustomUserRole>
{
    public CustomRole() { }
    public CustomRole(string name) { Name = name; }
}

public class CustomUserRole : IdentityUserRole<string> { }
public class CustomUserClaim : IdentityUserClaim<string> { }
public class CustomUserLogin : IdentityUserLogin<string> { }

// define the application user
public class ApplicationUser : IdentityUser<string, CustomUserLogin, CustomUserRole, 
    CustomUserClaim>
{
    [Required]
    public bool IsActive { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;


    }
}

public partial class myDbContext : IdentityDbContext<ApplicationUser, CustomRole, string, 
    CustomUserLogin, CustomUserRole, CustomUserClaim>
{
    static myDbContext()
    {
        Database.SetInitializer<myDbContext>(null);
    }

    public myDbContext()
        : base("Name=myDbContext")
    {
    }

    public DbSet<TestTable> TestTables { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new TestTableMap());
    }
}

I then have this code:

// create the user manager
        UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser, CustomRole, string, CustomUserLogin, CustomUserRole,
    CustomUserClaim>(
            new myDbContext()));

I get an error in this statement saying the argument type UserStore<-ApplicationUser, CustomRole, string, CustomUserLogin, CustomUserRole, CustomUserClaim-> is not assignable to the parameter type IUserStore<-ApplicationUser->

What am I missing here?

like image 339
user1206480 Avatar asked Dec 14 '22 23:12

user1206480


1 Answers

try this:

UserManager = new UserManager<ApplicationUser,string>(new UserStore<ApplicationUser, CustomRole, string, CustomUserLogin, CustomUserRole, CustomUserClaim>(new myDbContext()));

note I use a different construction for UserManager, I added string as a second type that you use in your code for ApplicationUser primary key

Since you implemented custom user/roles/etc the way you did, you'll need to use UserManager as UserManager<ApplicationUser,string> throughout your code to pass in the type for User PK as a string.

like image 165
dima Avatar answered Jan 07 '23 20:01

dima