Skip to content

Instantly share code, notes, and snippets.

@M-Yankov
Last active March 30, 2019 13:28
Show Gist options
  • Save M-Yankov/e85981159c00d37047b06fd72791697c to your computer and use it in GitHub Desktop.
Save M-Yankov/e85981159c00d37047b06fd72791697c to your computer and use it in GitHub Desktop.
Get services from scope with IWebHost
// ASP Net Core 2.2.2
// Get registered services from WebHost instance.
// In case the IServiceCollection or ApplicationBuilder is not available in the current context.
// The method can be used in separate assembly
pulbic void TestMethod()
{
using (IServiceScope scope = this.webHost.Services.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
RoleManager<IdentityRole> roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
}
}
// Source: https://github.com/aspnet/Mvc/issues/4783#issuecomment-381978090
@M-Yankov
Copy link
Author

M-Yankov commented Mar 30, 2019

For RoleManager<IdentityRole>, the AddRoles() method should be used:

services.AddDefaultIdentity<IdentityUser>()
      .AddRoles<IdentityRole>()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment