无法访问已处置的对象。但我刚刚创建了对象,并试图在下一行代码中将其保存到数据库中

Cannot access disposed object. But I just created the object, and am trying to save it to the database on the very next line of code

我正在制作一个登录系统。 CheckCredentials() 方法从登录表单获取数据:

public async Task<IActionResult> CheckCredentials(LoginFormViewModel loginForm)
{
    if (loginForm == null) return NotFound();

    AdminUser au = await db.AdminUsers
        .Include(p => p.Person)
        .Where(u =>
            u.Person.Email1 == loginForm.UserName &&
            u.Password == loginForm.Password)
        .FirstOrDefaultAsync().ConfigureAwait(false);
    if (au != null)
    {
        LogInAdminUser(au);
        return RedirectToLocal(loginForm.ReturnUrl ?? au.StartPage ?? "/Admin");
    }

    TempData["Message"] = "No such combination of username and password exists. Please try again.";
    return RedirectToAction("Login", new { loginForm.ReturnUrl });
}

如果找到与给定凭据匹配的 AdminUser,则调用 void 方法 LogInAdminUser()

private async void LogInAdminUser(AdminUser au)
{
    HttpContext.Session.SetInt32("AdminUserId", au.Id);
    Login login = new Login
    {
        PersonId = au.PersonId,
        AdminUserId = au.Id,
        LogInTime = DateTime.Now,
        RemoteIpAddress = "some string",
        Browser = "some string"
    };
    db.Add(login);
    await db.SaveChangesAsync().ConfigureAwait(false); // This line causes the exception below
    return;
}

此异常在 SaveChangesAsync() 上抛出:

System.ObjectDisposedException: '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. ObjectDisposed_ObjectName_Name'

Login-class:

public class Login
{
    public int Id { get; set; }
    public int PersonId { get; set; }
    public int? AdminUserId { get; set; }
    public DateTime LogInTime { get; set; }
    public string RemoteIpAddress { get; set; }
    public string Browser { get; set; }
    public AdminUser AdminUser { get; set; }
}

这里发生了什么?我没有在我的代码中的任何地方 Disposeing 任何东西。

更新

这是我创建数据库上下文的方式:

public class AdminController : BaseController
{
    private readonly KlubbNettContext db;
    private readonly IMapper auto;

    public AdminController(KlubbNettContext context, IMapper mapper, IHostingEnvironment env) : base(env)
    {
        db = context;
        auto = mapper;
    }

    // The rest of the controller methods here.
    // Both CheckCredentials() and LogInAdminUser() are among the
    // methods of this controller.
}

LoginAdminUser 是异步的,但是当你调用它时你并没有等待它。结果,操作的处理继续进行并且 returns 在 LoginAdminUser 完成之前。当操作 returns 时,上下文被释放给你异常。

多空,静候召唤:

if (au != null)
{
    await LogInAdminUser(au);
    return RedirectToLocal(loginForm.ReturnUrl ?? au.StartPage ?? "/Admin");
}