Multiple calls to userManager result in Disposed error
I have this code that's called from Startup.Configure:
public async void Initialize()
{
appDbContext.Database.EnsureCreated();
var adminGroupName = "Administrator";
if (appDbContext.Roles.All(i => i.Name != adminGroupName))
{
await roleManager.CreateAsync(new IdentityRole(adminGroupName));
};
var role = appDbContext.Roles.First(i => i.Name == adminGroupName);
if (appDbContext.Users.All(i => i.UserName != adminSettings.Username))
{
await userManager.CreateAsync(new ApplicationUser { UserName = adminSettings.Username,
Email = adminSettings.Username,
FirstName = adminSettings.FirstName,
LastName = adminSettings.LastName,
EmailConfirmed = true }, adminSettings.Password);
}
var adminUser = appDbContext.Users.First(i => i.UserName == adminSettings.Username);
if (!appDbContext.UserRoles.Any(i => i.RoleId == role.Id && i.UserId == adminUser.Id))
{
await userManager.AddToRoleAsync(adminUser, role.Name);
}
}
At random, I get the Accessing Disposed Exception from userManager.CreateAsync or userManager.AddToRoleAsync
The class where Initialize is declared is registered with AddScoped in Startup.ConfiguredServices and is passed as an argument to Startup.Configure.
What am I doing wrong that I am getting the Disposed exceptions?
Thank you.
Can we see your complete startup.Configure? Where is your user manager coming from? Is this called on every request? UserManager et al are request scoped.
Are you trying to seed data here?
DbInitializer.Initialized is called from Startup.Configure. I hope it's called only once, not on every request. Yes, I am trying to seed the admin account for the site. Normally, I seed using MERGE SQL statements, but in this case of creating an account, it seemed that using UserManager from .NET core code is better.
Here is my Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyGroupDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyGroupDbConnection")));
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyGroupDbConnection")));
services.Configure<AdminSettings>(Configuration.GetSection("settings").GetSection("admin"));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
services.AddScoped<IDbInitializer, DbInitializer>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IDbInitializer dbInitializer)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
dbInitializer.Initialize();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
User manager is injected into DbInitializer:
public class DbInitializer : IDbInitializer
{
private readonly UserManager<ApplicationUser> userManager;
private readonly RoleManager<IdentityRole> roleManager;
private readonly AdminSettings adminSettings;
private readonly ApplicationDbContext appDbContext;
public DbInitializer(
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager,
IOptions<AdminSettings> optionsAccessor,
ApplicationDbContext appDbContext)
{
this.appDbContext = appDbContext;
this.userManager = userManager;
this.roleManager = roleManager;
adminSettings = optionsAccessor.Value;
}
Thanks
Something along those lines....scope the objects inside the configure.
var roleManager = app.ApplicationServices.GetService<RoleManager<IdentityRole>>();
foreach (var role in Roles.All) {
}
Also async void is not a good pattern. Return a Task and wait if needed.
@popsovy Looks like this is happening because the DbContext, which is registered as scoped, is being accessed from the root scope. However, these is not enough code to be sure--if this isn't the case, then please post a runnable project/solution of complete code listing that demonstrates the issue and we will re-open and investigate further.