实体框架,UnitofWork模式与dispose方法

时间:2015-07-27 21:15:32

标签: 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的成员,在范围之外它将由garbace收集器自动处理。那么,我们为什么要手动执行此操作?举个例子:

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

2 个答案:

答案 0 :(得分:3)

在范围之外,变量不再可达,但并不意味着处置。根据经验,应该处理每个实现IDisposable的类。在EF的情况下,它将清除缓存,跟踪对象更改的图形以及回滚任何未提交的事务。

答案 1 :(得分:2)

使用GC,您不知道何时启动GC。即使变量超出范围,也不意味着它已被垃圾收集。使用配置模式,您可以立即释放内存。

From MSDN:在确定何时安排垃圾收集时,运行时会考虑分配的内存内存量。如果小型托管对象分配大量非托管内存,则运行时仅考虑托管内存,因此低估了调度垃圾回收的紧迫性。

因此,对于拥有本机资源的托管对象,您应该调用dispose来释放本机资源。

相关问题