【问题标题】:Entity Framework, UnitofWork pattern with dispose method实体框架,带有 dispose 方法的 UnitofWork 模式
【发布时间】:2015-07-27 21:15:32
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 只是补充一下,它会被释放,但只有在请求 GC 释放内存并且部分内存是 dbContext 实例时。有些情况只在应用程序退出时发生,因为不使用很多资源。正如马特所说,取决于 GC 的紧迫性及其背后的算法。
    • Dispose 并不意味着它会被垃圾收集。 Dispose 意味着将要处理一些资源,例如关闭数据库连接。垃圾收集器从内存中清除对象,这是不同的。
    【解决方案2】:

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

    来自MSDN:在确定何时安排垃圾回收时,运行时会考虑分配了多少托管内存。如果一个小的托管对象分配了大量的非托管内存,运行时只考虑托管内存,从而低估了调度垃圾回收的紧迫性。

    所以对于持有原生资源的托管对象,你应该调用 dispose 来释放原生资源。

    【讨论】:

    • 不,但它拥有无人资源,例如数据库连接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多