Dillinger
Dillinger

Reputation: 1903

How to use identity?

Description

I'm learning ASP.NET Core with MVC pattern and I'm trying to create a custom Roles for my users.

Code

For doing this I setup inside the ConfigureServices method this Identity:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<MyAppContext>(options => options.UseSqlServer(@"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MyApp;Integrated Security=True;Connect Timeout=30;"));

    services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<MyAppContext>()
            .AddDefaultTokenProviders();
}

then inside the Configure method I declare this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   new UserRoleSeed(app.ApplicationServices.GetService<RoleManager<IdentityRole>>()).SeedAsync();
}

Essentially I used the Dependency Injection to pass the RoleManager in the UserRoleSeed constructor, which is a configuration class for the role:

public class UserRoleSeed
{
    private readonly RoleManager<IdentityRole> _roleManager;

    public UserRoleSeed(RoleManager<IdentityRole> roleManager)
    {
        _roleManager = roleManager;
    }

    public async void SeedAsync()
    {
        if ((await _roleManager.FindByNameAsync("Admin")) == null)
        {
            await _roleManager.CreateAsync(new IdentityRole { Name = "Admin" });
        }
    }
}

when I start the application I get this error:

System.InvalidOperationException: 'Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]' from root provider.'

What I did wrong?

NB: I added only the relevant code.

Upvotes: 0

Views: 155

Answers (1)

Edward
Edward

Reputation: 30056

There are two issues in your code:

  1. resolving RoleManager<IdentityRole> from root provider
  2. SeedAsync will cause object dispose error.

Try steps below to resolve your issue:

  1. Add IServiceProvider to Configure

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
    
  2. Modify SeedAsync from void to Task

        public async Task SeedAsync()
    
  3. Call SeedAsync from Configure

    new UserRoleSeed(serviceProvider.GetService<RoleManager<IdentityRole>>()).SeedAsync().Wait();
    

Upvotes: 1

Related Questions