public enum RepositoryType
{
ClinicRepository,
MedicationRepository,
PatientRepository,
TreatmentRepository
}
public class ObjectFactory<T>
{
public static IRepository<T> GetRepositoryInstance(RepositoryType type)
{
switch (type)
{
case RepositoryType.ClinicRepository:
return new what ?;
default:
return what ?
}
}
}
public interface IRepository<T>
{
void Add(T item);
void Remove(int id);
void Update(T item);
IList<T> GetAll();
T GetItemById(int id);
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试创建一个RepositoryFactory类,我复制了迄今为止我所做的事情.有人可以帮我解决这个问题吗?我被卡住了!提前致谢
编辑:
我最终想要这样的东西.是否可以制作1个Repository类并实现类似的东西
dc.THATOBJECT.insertonsubmit(item)?
public class TreatmentRepository : IRepository<Treatment>
{
public void Add(Treatment item)
{
using (PatientsDataContext dc = new PatientsDataContext())
{
dc.Treatments.InsertOnSubmit(item);
dc.SubmitChanges();
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*k H 13
最简单的工厂只需要从IRepository派生的类型具有无参数构造函数.
public class ObjectFactory {
public static TRepository GetRepositoryInstance<T, TRepository>()
where TRepository : IRepository<T>, new() {
return new TRepository();
}
}
Run Code Online (Sandbox Code Playgroud)
如果需要特定存储库类型的特定构造函数,则可以将对象指定为对象数组并使用它们创建它们 CreateInstance
public class ObjectFactory {
public static TRepository GetRepositoryInstance<T, TRepository>(
params object[] args)
where TRepository : IRepository<T> {
return (TRepository)Activator.CreateInstance(typeof(TRepository), args);
}
}
Run Code Online (Sandbox Code Playgroud)
要使用其中任何一种,您只需要说
var treatmentRepo =
ObjectFactory.GetRepositoryInstance<Treatment, TreatmentRepository>();
Run Code Online (Sandbox Code Playgroud)
要有东西返回,你需要编写一个实现的类IRepository<T>.
public class SomeKindOfRepository<T> : IRepository<T>
{
public void Add(T item)
{
}
// and so on...
}
Run Code Online (Sandbox Code Playgroud)
它似乎有四种广泛的类型(ClinicRepository,MedicationRepository等) - 它们在"存储"事物方面有很大不同吗?如果是这样,请为每个人单独创建一个类.否则,使用具有某些字段的相同类来控制其行为.
更新
根据您的编辑和注释,您有一个存储库,它实际上是对表的一些操作.唯一真正变化的是它包裹的桌子.但该表是数据上下文的成员.因此,您可以将表的选择推迟到派生类.
这将是基类:
public class GeneralRepository<TEntity, TContext> : IRepository<TEntity>
{
protected abstract Table<TEntity> GetTable(TContext dc);
public void Add(Treatment item)
{
using (TContext dc = new TContext())
{
GetTable(dc).InsertOnSubmit(item);
dc.SubmitChanges();
}
}
// and so on for other methods
}
Run Code Online (Sandbox Code Playgroud)
派生类只需指定如何从上下文中选择表:
public class TreatmentsRepository : GeneralRepository<Treatment, PatientsDataContext>
{
protected override Table<Treatment> GetTable(PatientsDataContext dc)
{
return dc.Treatments;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16169 次 |
| 最近记录: |