[英]How to implement Save in an in-memory repository
我有以下代码
foreach (var obj in MyList)
{
// BL
repository.Add(obj)
// BL
repository.Update(obj)
}
我有两个实现IRepository的类。 一类使用MsSql,另一类使用内存。 内存中的实现使用List来存储我的数据。 如果我使用MsSql类,则所有数据已存储在DB中。 如果使用内存,则需要在foreach循环之后将存储库列表中的所有数据插入DB。 我不确定明智的OOP最佳方法是什么。
我可以向IRepository中添加Save方法,但这意味着MsSql类将实现它不需要的方法。 另一种选择是仅在内存类中添加一个方法,然后执行以下操作:
IRepository rep = repository as InMemoryRepository
if (rep != null)
{
rep.Save()
}
你怎么看?
您应该在基本接口中具有所有存储库实现(MSSQL,内存中)通用的方法。
SaveToDatabase是一种非常针对内存的方法,应该属于InMemory存储库实现类。 不要将其作为基本接口的一部分,因为它对其他具体实现可能没有任何意义。
另一个选择是实现内存中存储库的persist方法,以便将其保存在列表中以及保存在数据库中。 (尽管这令人担忧)
public interface IRepository
{
void Add(MyType object);
}
public class SqlRepository : IRepository
{
public void Add(MyType object)
{
// saves to DB
}
}
public class InMemoryRepository : IRepository
{
List<MyType> store = new List<MyType>();
public void Add(MyType object)
{
// saves to list store.
// may also, additionally store to DB.
IRepository dbRep = DependencyInjection.GiveMeDatabaseRepository<IRepository>();
// null check so that if tomorrow, there is no SQL repository, this code doesn't break.
if (dbRep != null )
{
dbRep.Add(object);
}
}
// this is another explicit option
public void AddToDatabase(MyType object)
{
IRepository dbRep = DependencyInjection.GiveMeDatabaseRepository<IRepository>();
dbRep.Add(object);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.