大佬教程收集整理的这篇文章主要介绍了ASP.NET Core 中的 DbContext 抛出 System.ObjectDisposedException,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在 ASP.NET Core 应用程序中使用 EF Core 将 Todo 模型保存到数据库。
但是当我尝试使用 Console.Writeline
打印成功消息时,它会抛出 System.ObjectdisposedException
这是完整的应用程序 github code link
这是 Todo 模型:
public class Todo
{
public int id { get; set; }
[required]
[MaxLength(10)]
public String title { get; set; }
public bool IsCompleted { get; set; } = false;
}
这里是抛出异常的业务逻辑。
using System;
using System.Collections.Generic;
using System.linq;
using System.Threading.Tasks;
using TodoApp.Models;
using TodoApp.Data;
namespace TodoApp
{
public class Todoservice
{
Readonly TodoContext _context;
public Todoservice(TodoContext context)
{
_context = context;
}
public async Task<int> CreatetoDo(CreatetodobindingModel input)
{
Todo todo = new()
{
title = input.title,IsCompleted = input.IsCompleted
};
_context.Add(todo);
await _context.SaveChangesAsync();
Console.Writeline("successfully saved todo.");
return task.ID;
}
}
}
异常详情:
System.ObjectdisposedException
HResult=0x80131622
message=CAnnot access a disposed context instance. A common cause of this error is disposing a context instance 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 instance,or wrapPing it 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: 'TodoContext'.
source=Microsoft.EntityFrameworkCore
StackTrace:
at Microsoft.EntityFrameworkCore.DbContext.checkdisposed()
Console.Writeline 为什么会抛出异常?
编辑: 这是 TodoContext:
public class TodoContext: DbContext
{
public TodoContext(DbContextoptions<TodoContext> options)
: base(options)
{ }
public DbSet<Todo> Todos { get; set; }
}
以下是它在 Startup.cs 中的注册方式:
public voID Configureservices(IserviceCollection services)
{
services.AddRazorPages();
var connectionString = Configuration["ConnectionString"];
services.AddDbContext<TodoContext>(options => optionS.UseNpgsql(connectionString));
services.AddScoped<Todoservice>();
}
这是完整的应用程序 github code link
问题出在您代码的这一部分:
public IActionResult OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
Task<int> id = _service.CreateTask(Input);//<--- this line
return RedirectToPage("Index");
}
调用返回任务后的 createTask 意味着尚未完成并且您不等待它完成,当调用 RedirectToPage
当前请求完成时。因为您的服务和 dbcontext 以 Scope
生命周期添加到 DI,这意味着对象的生命周期在请求期间,当请求完成时,该对象将被处理。
所以解决问题就用这种方式:
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
int id = await _service.CreateTask(Input);
return RedirectToPage("Index");
}
以上是大佬教程为你收集整理的ASP.NET Core 中的 DbContext 抛出 System.ObjectDisposedException全部内容,希望文章能够帮你解决ASP.NET Core 中的 DbContext 抛出 System.ObjectDisposedException所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。