首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RoleManager在Asp.Net内核2中的种子角色

RoleManager在Asp.Net内核2中的种子角色
EN

Stack Overflow用户
提问于 2018-03-20 10:08:08
回答 1查看 2.1K关注 0票数 1

我一直在使用这个链接来播种我的数据库。

带AspNet核的数据库种子

现在,在播种时,我还想访问UserManager<ApplicationUser>RoleManager<IdentityRole>

但是,由于这是在配置方法中调用的,所以我无法使用;

var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();

var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();

我将如何访问这个注入,以便我可以种子我的角色,等等?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-20 10:30:16

为了给你一个提示,我在我们的Startup.cs中使用了这个。我希望这能帮到你。

代码语言:javascript
复制
// Inside the public void Configure(IApplicationBuilder app)

var scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();

var scope = scopeFactory.CreateScope();

var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();

new UserRoleSeed(roleManager).Seed(); // Where UserRoleSeeding happens

您还需要在IdentityDbContext<ApplicationUser>中继承这个DbContext。类似于下面的示例代码:

代码语言:javascript
复制
public class ProjectDbContext : IdentityDbContext<ApplicationUser>

在您的控制器中实现此功能时,我建议您使用类似于下面代码的依赖注入:

代码语言:javascript
复制
private readonly UserManager<ApplicationUser> userManager;
private readonly RoleManager<IdentityRole> roleManager;

public TestingController(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager){
   this.userManager = userManager;
   this.roleManager = roleManager;
}

public async Task<IActionResult> Index(){
   // Test in getting userManager
   var user = await userManager.GetUserAsync(HttpContext.User);
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49381335

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档