DacorieS DacorieS - 3 years ago 96
C# Question

Cannot access a disposed object Object name: 'UserManager`1'

I realize that this question is ask quite a few times on stack Overflow but i tried a few answer but non solve my issue.I just recently added unity into my project, everything work fine except for the userManager class. If i try to access it in session it throws a Cannot access error as stated in my title.

The Code that is throwing the issues and the Container below

public AccountController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;

// Start of new code
UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager)
{
AllowOnlyAlphanumericUserNames = false,
};
}



container.RegisterType<AdminController>();
container.RegisterType<AccountController>();
container.RegisterType<IBlogPostRepository, BlogPostRepository>(new HierarchicalLifetimeManager());
container.RegisterType<IBlogViewRepository, BlogViewRepository>(new HierarchicalLifetimeManager());
container.RegisterType<ITagRepository, TagRepository>(new HierarchicalLifetimeManager());
container.RegisterType<ICategoryRepository, CategoryRepository>(new HierarchicalLifetimeManager());
container.RegisterType<IBlogCategoryRepository, BlogCategoryRepository>(new HierarchicalLifetimeManager());
container.RegisterType<IBlogTagRepository, BlogTagRepository>(new HierarchicalLifetimeManager());
container.RegisterType<IApplicationUserRepository, ApplicationUserRepository>(new HierarchicalLifetimeManager());
container.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new InjectionConstructor(new CatchMediaContext()));
container.RegisterType<DbContext, CatchMediaContext>(new HierarchicalLifetimeManager());

Answer Source

If another object has a reference to userManager and that object is disposed, it might be disposing userManager along with it. Another possibility is userManager requires some type of initialization which hasn't been done yet, and its properties throw a misleading disposed exception (this is common with winform controls).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download