ASP.Net Core(MVC6)存储库模式意外处置

时间:2016-02-22 04:30:00

标签: c# asp.net asp.net-core asp.net-core-mvc

当我尝试添加评论时,出现以下错误:

  

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);

EDIT2:

在Startup.cs中,我将IcommentRepository注册为Scoped并按预期工作。最初是Singleton。为什么单身人士会导致这个问题?

services.AddSingleton<ICommentRepository, CommentRepository>(); //breaks
services.AddScoped<ICommentRepository, CommentRepository>(); //works

EDIT3:

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; }
}

1 个答案:

答案 0 :(得分:7)

您的存储库和DbContext都不应该是单身人士。注册它们的正确方法是services.AddScopedservices.AddTransient,因为DbContext的生命时间不应超过请求,而AddScoped正好适用于此。

AddScoped将在范围的生命周期内返回DbContext(以及存储库,如果您注册它)的相同实例(在ASP.NET Core中等于请求的生命周期) 。

使用AddScope时,您不应自行处理上下文,因为解析存储库的下一个对象将具有已处置的上下文。

实体框架默认情况下将上下文注册为作用域,因此您的存储库应该是作用域(与上下文和请求相同的生命周期)或瞬态(每个服务实例获取它自己的存储库实例,但是所有存储库在请求中仍然共享相同的上下文)。

制作上下文单例会导致严重的问题,特别是对于内存(你对它的工作越多,上下文消耗的内存就越多,因为它必须跟踪更多的记录)。所以DbContext应尽可能短暂。

上下文的持续时间具有以下优点:如果出现问题,您仍可以在请求期间回滚所有操作并将其作为单个事务处理。