[英]'Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection
[英]Error: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection
我正在 dotnet core 2.2 上開發一個應用程序
自從兩天以來,我一直在受這個如此著名的問題的困擾。 我一次又一次地修改了以下鏈接,但這些似乎不起作用:
但似乎沒有什么能解決問題。
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;
}
}
以下異常發生在 ** 行。
無法訪問已處置的對象。 此錯誤的一個常見原因是處理從依賴注入解析的上下文,然后嘗試在應用程序的其他地方使用相同的上下文實例。 如果您在上下文上調用 Dispose() 或將上下文包裝在 using 語句中,則可能會發生這種情況。 如果你使用依賴注入,你應該讓依賴注入容器來處理上下文實例。 對象名稱:'ApplicationDbContext'。
以下是我的 Program.cs 文件
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>();
}
編輯:堆棧跟蹤:
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
我在調用函數 await _userAccountBL.AddUser(user); 時缺少 await 關鍵字;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.