Remove your change in web.config and in Startup.Auth add the following reference to ConfigureAuth:
public void ConfigureAuth(IAppBuilder app) { app.CreatePerOwinContext(ApplicationDbContext.Create); // Add this reference to RoleManager (without changing any other items) // Make sure it is added below ApplicationDbContext.Create app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create); }
Then in your Controller, make sure it includes this in the constructor:
public class YourController : Controller { // Add this private ApplicationRoleManager _roleManager; // Add roleManager public YourController(ApplicationRoleManager roleManager) { // Add this RoleManager = roleManager; } public ApplicationRoleManager RoleManager { get { return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>(); } private set { _roleManager = value; } } }
and also include this in the Controller's Dispose (if you have it):
protected override void Dispose(bool disposing) { if (disposing) { // include this if (_roleManager != null) { _roleManager.Dispose(); _roleManager = null; } } base.Dispose(disposing); }
You may also need to add this code to IdentityConfig (in the App_Start folder if you're using the template):
public class ApplicationRoleManager : RoleManager<IdentityRole> { public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore) : base(roleStore) { } public static ApplicationRoleManager Create( IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context) { var manager = new ApplicationRoleManager( new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>())); return manager; } }
You should now be able to use the RoleManager in the Controller.