[英]Entity Framework, UnitofWork pattern with dispose method
样本:
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,它将清除高速缓存,跟踪对象更改的图形并回滚所有未提交的事务。
使用GC,您不知道何时启动GC。 即使变量超出范围,也不意味着它已被垃圾回收。 使用处置模式,您可以立即释放内存。
来自MSDN :在确定何时安排垃圾回收时,运行时将考虑分配了多少托管内存。 如果一个小的托管对象分配了大量的非托管内存,则运行时仅考虑托管内存,因此低估了调度垃圾回收的紧迫性。
因此,对于保存本地资源的托管对象,应调用dispose释放本地资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.