c# - Entity Framework ,带有 dispose 方法的 UnitofWork 模式

标签 c# entity-framework dbcontext unit-of-work

uow 的示例:

using System;
using ContosoUniversity.Models;

namespace ContosoUniversity.DAL
{
    public class UnitOfWork : IDisposable
    {
        private SchoolContext context = new SchoolContext();
        private GenericRepository<Department> departmentRepository;
        private GenericRepository<Course> courseRepository;

        public GenericRepository<Department> DepartmentRepository
        {
            get
            {

                if (this.departmentRepository == null)
                {
                    this.departmentRepository = new GenericRepository<Department>(context);
                }
                return departmentRepository;
            }
        }

        public GenericRepository<Course> CourseRepository
        {
            get
            {

                if (this.courseRepository == null)
                {
                    this.courseRepository = new GenericRepository<Course>(context);
                }
                return courseRepository;
            }
        }

        public void Save()
        {
            context.SaveChanges();
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}

如您所见,uow 包含 dispose 方法,并在其中处理 dbContex 对象。为什么我们应该显式处置 dbContext 对象。由于它是uow的成员,在范围之外它将被垃圾收集器自动处理。那么,我们为什么要手动执行此操作?举个例子:

using(Uow uowObject = new Uow())
{
      //there is a dbcontext
}
  //it will be disposed automaticly by gc

最佳答案

在作用域之外,变量不再可访问,但这并不意味着已释放。根据经验,每个实现 IDisposable 的类都应该被释放。对于 EF,它将清除缓存、跟踪对象更改的图表并回滚任何未提交的事务。

关于c# - Entity Framework ,带有 dispose 方法的 UnitofWork 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31663459/

相关文章:

C#,是否可以在没有副本的情况下将 byte* 转换为 byte[]?最快的方法是什么?

c# - 如何使用 C# 在运行时创建类的新实例?

c# - 使用自动生成的 Poco 实体

c# - 将 DbContext 拆分为具有重叠 DbSet 的多个上下文

C# 字节类型和文字

c# - 使用 FileSystemWatcher 观察 log4net 日志文件

c# - ffmpeg 使用 c# avformat_open 运行失败

entity-framework - Entity Framework - Azure 上的迁移 - 现实场景 - 降级数据库

c# - 无法向 Unity 和 Entity Framework 注册 DbConnection

asp.net-mvc - 如何从 MVC 业务对象中引用 Entity Framework DbContext?