I am developing an application on .NET Core 2.2 and have run into an issue:
Error: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection
I have reviewed the following links, but these don't seem to work:
- Cannot access a disposed object in ASP.NET Core when injecting DbContext
- Cannot access a disposed object. A common cause of this error is disposing a context
- https://thinkrethink.net/2017/12/22/cannot-access-a-disposed-object-in-asp-net-core-when-injecting-dbcontext/
Here is my code:
public class UserAccountController : BaseController
{
private readonly UserAccountBL _userAccountBL;
public UserAccountController(IConfiguration configuration,
ILogger<UserAccountBL> logger, ApplicationDbContext db, UserManager<AppUser> accountManager)
{
_userAccountBL = new UserAccountBL(configuration,logger,db, accountManager);
}
[HttpPost("addnewUser")]
public async Task<IActionResult> AddNewUser(UserVM user)
{
try
{
var result = _userAccountBL.AddUser(user);
return Ok(result);
}
catch(NotFoundException e)
{
return Ok(new NotFoundError(e.Message));
}
}
}
public class DeliveryManagerAccountBL
{
private readonly IConfiguration _configuration;
private readonly ILogger<UserAccountBL> _logger;
private readonly ApplicationDbContext _context;
private readonly UserManager<AppUser>_accountManager;
public UserAccountBL(IConfiguration configuration,
ILogger<UserAccountBL> logger, ApplicationDbContext db, UserManager<AppUser> accountManager)
{
_configuration = configuration;
_logger = logger;
_context = db;
_accountManager = accountManager;
}
public async Task<bool> AddUser( AddRiderVM user)
{
if (CheckEmailExist(model.EmailAddress))
{
throw new InvalidOperationException("Email already exist");
}
if (CheckPhoneExist(model.MobileNumber))
{
throw new InvalidOperationException("Mobile number already exist");
}
var newUserID = Guid.NewGuid().ToString();
var user = new AspNetUser
{
UserName = user.EmailAddress,
Email = user.EmailAddress,
Id = newUserID,
PhoneNumber = user.MobileNumber
};
var password = "Dumy123@";
try
{
List<string> roles = new List<string>();
**var result = await _accountManager.CreateAsync(user, password);**
if (result.Succeeded)
{
//Something will happen
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return false;
}
}
Following is my Program.cs file:
public class Program
{
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
//seed database
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var databaseInitializer = services.GetRequiredService<IDatabaseInitializer>();
databaseInitializer.SeedAsync().Wait();
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogCritical(LoggingEvents.INIT_DATABASE, ex, LoggingEvents.INIT_DATABASE.Name);
throw new Exception(LoggingEvents.INIT_DATABASE.Name, ex);
}
}
host.Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
The following exception occurs at the ** line.
Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances. Object name: 'ApplicationDbContext'.
Stack Trace:
at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
at Microsoft.EntityFrameworkCore.DbContext.<SaveChangesAsync>d__53.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.<CreateAsync>d__22.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Microsoft.AspNetCore.Identity.UserManager`1.<CreateAsync>d__74.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Microsoft.AspNetCore.Identity.UserManager`1.<CreateAsync>d__79.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at StilaarApi.Core.AccountManager.<CreateUserAsync>d__10.MoveNext() in D:\project stilaar\pinchapi\Core\AccountManager.cs:line 106