我总是创建一个 DataContextFactory ,它将我自己的接口传递给上下文,并将其传递给我的存储库,如下所示:
上下文接口:
public IMyDataContext {
// One per table in the database
IDbSet<Class1> Class1s { get;set; }
// etc
// The standard methods from EF you'll use
void Add( object Entity );
void Attach( object Entity );
void Delete( object Entity );
void SaveChanges();
}
上下文工厂:
public class MyDataContextFactory : IMyDataContextFactory {
public IMyDataContext GetContext() {
// TODO: Use the service locator pattern to avoid the direct instanciation
return new MyDataContext();
}
}
上下文工厂接口:
public interface IMyDataContextFactory {
IMyDataContext GetContext();
}
存储库:
public class MyClass1Repository {
private readonly IMyDataContextFactory factory;
public MyClass1Repository( IMyDataContextFactory Factory ) {
// TODO: check for null
this.factory = Factory;
}
public List<MyClass1> GetAll() {
using ( IMyDataContext db = this.factory.GetContext() ) {
return db.Class1s.ToList();
}
}
// TODO: Other methods that get stuff
}
然后,当我想测试存储库时,我传入IMyDataContextFactory
一个IMyDataContext
从GetContext()
.
随着时间的推移,我注意到存储库中的重复,并且可以将某些方法推送到基本存储库中:GetAll()
, Save()
,GetById()
有时如果我有一致的主键等。