Solarion
Honorary Master
- Joined
- Nov 14, 2012
- Messages
- 28,050
- Reaction score
- 17,804
I've come across dozens of articles where this pattern is implemented in various different ways.
A reply by the user Lars-Evik has it as such
I found this example on a blog
And finally this example by Microsoft's Tom Dykstra. The newing up of the GenericRepository did raise an eyebrow.
Please could you guys advise on what is the correct way to do this. What do you do?
A reply by the user Lars-Evik has it as such
C#:
public class EFUnitOfWork : IUnitOfWork
{
private readonly DbContext context;
public EFUnitOfWork(DbContext context)
{
this.context = context;
}
internal DbSet<T> GetDbSet<T>()
where T : class
{
return context.Set<T>();
}
public void Commit()
{
context.SaveChanges();
}
public void Dispose()
{
context.Dispose();
}
}
I found this example on a blog
C#:
public class UnitOfWork : IUnitOfWork
{
protected string ConnectionString;
private MovieContext context;
public UnitOfWork(string connectionString)
{
this.ConnectionString = connectionString;
}
public MovieContext DbContext
{
get
{
if (context == null)
{
context = new MovieContext(ConnectionString);
}
return context;
}
}
public int Save()
{
return context.SaveChanges();
}
public void Dispose(bool disposing)
{
if (disposing)
{
if (context != null)
{
context.Dispose();
context = null;
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
And finally this example by Microsoft's Tom Dykstra. The newing up of the GenericRepository did raise an eyebrow.
C#:
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);
}
}
Please could you guys advise on what is the correct way to do this. What do you do?