I'm trying to use unit of work and repository in my project. Which then got me thinking on how to implement transaction with it.
At the moment this is what I plan to do :
public class UnitOfWork : IUnitOfWork
{
private readonly IDbFactory databaseFactory;
private adminBoContext dataContext;
private DbContextTransaction _transaction;
private Repository<a> repoA;
....
private Repository<x> repoX;
public UnitOfWork(IDbFactory databaseFactory)
{
this.databaseFactory = databaseFactory;
_transaction = dataContext.Database.BeginTransaction();
}
protected Context DataContext
{
get { return dataContext ?? (dataContext = databaseFactory.Get()); }
}
public void Commit()
{
try
{
_transaction.Commit();
}
catch (Exception ex)
{
_transaction.Rollback();
}
}
}
but then I also come across example such as SocialGoal project where it has Unit of works (but without repositories inside it) and separate repositories that looks like has its own instance of the context
public class UnitOfWork : IUnitOfWork
{
private readonly IDatabaseFactory databaseFactory;
private SocialGoalEntities dataContext;
public UnitOfWork(IDatabaseFactory databaseFactory)
{
this.databaseFactory = databaseFactory;
}
protected SocialGoalEntities DataContext
{
get { return dataContext ?? (dataContext = databaseFactory.Get()); }
}
public void Commit()
{
DataContext.Commit();
}
}
public abstract class RepositoryBase<T> where T : class
{
private SocialGoalEntities dataContext;
private readonly IDbSet<T> dbset;
protected RepositoryBase(IDatabaseFactory databaseFactory)
{
DatabaseFactory = databaseFactory;
dbset = DataContext.Set<T>();
}
protected IDatabaseFactory DatabaseFactory
{
get;
private set;
}
protected SocialGoalEntities DataContext
{
get { return dataContext ?? (dataContext = DatabaseFactory.Get()); }
}
public virtual void Add(T entity)
{
dbset.Add(entity);
}
I'm really confuse now at how actually unit of work and repository should be implemented, because as I understand that unit of work will be kind of the main gate which all the access to repositories will pass through.
I would very appreciate it if someone could shed some light on this unit of work and repository implementation.
Thank you so much.