Home > Software design >  ASP .net create Role problem with RoleManager
ASP .net create Role problem with RoleManager

Time:06-07

I'm writing ASP.Net app using Jetbrains Rider. I'm using Identity. Mine ApplicationDbContext looks like that:

public class BoardGameNETProjectContext : IdentityDbContext<IdentityUser>

{

public BoardGameNETProjectContext(DbContextOptions<BoardGameNETProjectContext> options)
    : base(options)
{
}

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);
    // Customize the ASP.NET Identity model and override the defaults if needed.
    // For example, you can rename the ASP.NET Identity table names and more.
    // Add your customizations after calling base.OnModelCreating(builder);
}

}

And in Program.cs i have this line:

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new BoardGameNETProjectContext()));

When I'm building I've got error message that parameter "options" is missing. I don't know how to fix that, I just wanted to add "Admin" role just like in this tutorial: link

CodePudding user response:

I assume that you are using asp.net 6 project - if so you can simply replace

var roleManager = new RoleManager<IdentityRole>(
    new RoleStore<IdentityRole>(
        new BoardGameNETProjectContext()));

with

// where you have this line
var app = builder.Build();

var scope = app.Services
    .GetService<IServiceScopeFactory>()
    ?.CreateScope();

if (scope is not null)
{ 
    using (scope)
    {
        var roleManager = scope
            .ServiceProvider
            .GetService<RoleManager<IdentityRole>>();

        // .. then use the RoleManager
    }
}

but you should ensure that you are adding the right identity:

services.AddIdentity<IdentityUser, IdentityRole>()

... instead of the Default Identity

  • Related