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/