Search code examples
c#asp.net-core.net-coreasp.net-core-identity

How to configure properly Identity core with DI on net.core 3.1?


I started a pet project on ASP.NET core 3.1 created MVC project and a bunch of libraries to work with.

I also created :

  • User,

  • Role,

  • RoleManager

  • UserManager

Classes which are inherited from AspNetCore.Identity. But I've got a problem while including those classes into DI container. Every time i get this InvalidOpertationException with info: Unable to resolve service for type Microsoft.AspNetCore.Identity.IUserStore while attempting to activate JournalUserManager.

Here's my code sample:

`services.AddIdentityCore<JournalUser>(options =>
 {
    options.User.RequireUniqueEmail = true;
    options.Lockout.MaxFailedAccessAttempts = 3;
    options.Password.RequireNonAlphanumeric = false;
    options.Password.RequireUppercase = false;
 })
   .AddRoles<JournalRole>()
   .AddRoleManager<JournalRoleManager>()
   .AddUserManager<JournalUserManager>();`

Any suggestions how to fix it?


Solution

  • Check out the custom storage providers guide

    In the Reconfigure app to use a new storage provider there is this example of setting up the IUserStore and the IRoleStore

    public void ConfigureServices(IServiceCollection services)
    {
        // Add identity types
        services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddDefaultTokenProviders();
    
        // Identity Services
        services.AddTransient<IUserStore<ApplicationUser>, CustomUserStore>();
        services.AddTransient<IRoleStore<ApplicationRole>, CustomRoleStore>();
        string connectionString = Configuration.GetConnectionString("DefaultConnection");
        services.AddTransient<SqlConnection>(e => new SqlConnection(connectionString));
        services.AddTransient<DapperUsersTable>();
    
        // additional configuration
    }