Why is my ApplicationDbContext getting disposed when I dispose of UserManager/RoleManager in my database initializer Seed()?
asp.net-identity, asp.net-mvc-5, entity-framework
Solution
It is the `RoleStore` that disposes the `DbContext` even if it did not create it. The `UserStore` has a `DisposeContext` bool property that controls if the context should be disposed or not. The `DisposeContext` is false if you use the constructor that takes a `DbContext` as input.
This seems to have been fixed in the nightly builds. Here the RoleStore also have the `DisposeContext` property and seems to work as expected.
Problem
I'm playing with MVC 5, and I've created a website that uses ASP.NET Identity. I followed the steps in this blog post on MSDN to create a user and a role in the `Seed` method for my database initializer. However, I noticed that the `UserManager` and `RoleManager` used in that code both implement IDisposable, so I changed the code slightly, to look something like this (and thus dispose them once I've finished with them): ``` protected override void Seed(ApplicationDbContext context) { using (var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context))) using (var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context))) { EnsureRoleCreated(roleManager, Roles.Administrator); const string AdministratorUserName = "admin"; const string DefaultAdminPassword = "password"; var user = EnsureUserCreated(userManager, AdministratorUserName, DefaultAdminPassword); EnsureUserIsInRole(userManager, user, Roles.Administrator); } base.Seed(context); } ``` Now, when my controller actions attempt to access the DB, I get an exception saying that my `DbContext` has been disposed. (I new up a `DbContext` instance in the constructor for my controller). [If I remove those `using()` statements and thus do not dispose the `UserManager` and `RoleManager`, then the problem goes away, so it's definitely those `using()` statements that are making the difference.] This seems very odd to me. If the "correct" way to deal with this is to not explicitly dispose the `UserManager` and `RoleManager`, then surely they will still be disposed eventually when the garbage collector kicks in. Since this is unpredictable and could happen at any time, does this not mean that I have a ticking time-bomb in my application? It seems to me that since I created the `DbContext`, I should be responsible for disposing of it. Why the heck are `UserManager` and/or `RoleManager` disposing of something they did not create?