【发布时间】:2016-02-22 04:30:00
【问题描述】:
当我尝试添加评论时,我收到以下错误:
ObjectDisposedException:无法访问已处置的对象。
当代码运行第二行时:
m_context.Comments.Add(comment);
m_context.SaveChanges();
为什么要处理上下文?如果将 TryAddComment 方法移动到控制器中,它不会提前调用 Dispose。
这是我的 Controller 和 Repository 类的样子(简化)。
CommentsController.cs:
public class CommentsController : Controller
{
private ICommentRepository m_commentRepository;
public CommentsController(ICommentRepository commentRepository)
{
m_commentRepository = commentRepository;
}
// POST: api/Comments
[HttpPost]
public async Task<IActionResult> PostComment([FromBody] CommentAddViewModel commentVM)
{
Comment comment = new Comment
{
ApplicationUserId = User.GetUserId(),
PostId = commentVM.PostId,
Text = commentVM.Text
};
bool didAdd = m_commentRepository.TryAddComment(comment);
if (!didAdd)
{
return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
}
return CreatedAtRoute("GetComment", new { id = comment.CommentId }, comment);
}
}
CommentRepository.cs:
public class CommentRepository : ICommentRepository, IDisposable
{
public ApplicationDbContext m_context;
public CommentRepository(ApplicationDbContext context)
{
m_context = context;
}
public bool TryAddComment(Comment comment)
{
m_context.Comments.Add(comment);
m_context.SaveChanges();
return true;
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
m_context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
编辑:
如果我使用本地 CommentRepository,它会按预期工作。例如:
CommentRepository localCommentRepo = new CommentRepository(m_context);
bool didAdd = localCommentRepo.TryAddComment(comment);
编辑2:
在 Startup.cs 中,我将 IcommentRepository 注册为 Scoped 并按预期工作。最初是辛格尔顿。为什么单例会导致这个问题?
services.AddSingleton<ICommentRepository, CommentRepository>(); //breaks
services.AddScoped<ICommentRepository, CommentRepository>(); //works
编辑3:
ApplicationDbContext.cs:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
public DbSet<Post> Posts { get; set; }
public DbSet<Comment> Comments { get; set; }
}
【问题讨论】:
-
请出示服务注册
-
添加服务注册
-
我们能看到 ApplicationDbContext 类的定义吗?因为它有可能实现了 Dispose 方法,所以 Add() 方法本身最后会销毁上下文对象。
-
-
添加了定义。
标签: c# asp.net asp.net-core asp.net-core-mvc