我有以下界面:
public interface IDatabaseFactory : IDisposable
{
MyDbContext Get();
}
public interface IUnitOfWork
{
void Commit();
}
public interface IRepository<T> where T : class
{
void Add(T entity);
void Update(T entity);
void Delete(T entity);
}
这是实施:
public class DatabaseFactory : IDatabaseFactory
{
private MyDbContext dataContext;
public MyDbContext Get()
{
return dataContext ?? (dataContext = new MyDbContext());
}
}
public class UnitOfWork : IUnitOfWork
{
private readonly IDatabaseFactory databaseFactory;
private MyDbContext dataContext;
public UnitOfWork(IDatabaseFactory databaseFactory)
{
this.databaseFactory = databaseFactory;
}
protected MyDbContext DataContext
{
get { return dataContext ?? (dataContext = databaseFactory.Get()); }
}
public void Commit()
{
DataContext.Commit();
}
}
public abstract class Repository<T> : IRepository<T> where T : class
{
private MyDbContext dataContext;
private readonly IDbSet<T> dbset;
protected Repository(IDatabaseFactory databaseFactory)
{
DatabaseFactory = databaseFactory;
dbset = DataContext.Set<T>();
}
protected IDatabaseFactory DatabaseFactory
{
get;
private set;
}
protected MyDbContext DataContext
{
get { return dataContext ?? (dataContext = DatabaseFactory.Get()); }
}
//method implementation...
}
使用MyDbContext时这很好用。但是,现在我添加了第二个实体集模型,我想增强上面的内容,以便我可以传递不同的上下文。
我怎样才能做到这一点?