我直接使用ADO.NET和MVC 5而不是实体框架。
我指的是这个example来实现Repository Pattern。
对于存储库模式的简单实现:
我想知道为什么使用Interface?我可以不按照上述第(3)点的规定直接使用课程。
界面有什么作用?
根据上述三点,是否正确实现了Repository Pattern?
答案 0 :(得分:2)
在设计良好的代码中,您必须使用接口,而不是实现。它有好处。想象一下,你有一个带有代码片段的类:
IBookRepository bookRepository;
public Book GetInterestingBook() {
var book = bookRepository.getBooks().FirstOrDefault(x => x.IsInteresting);
return book;
}
现在,我将向您展示一些好处:
使用interface允许您通过依赖注入(Ninject,Unity等)隐式创建bookRepository实例。其中有许多实例。如果您决定将存储库实现从Entity Framework更改为NHibernate,则不需要对代码进行更改。只需更改映射文件中的映射以用于IBookRepository NHibernateRepository而不是EFBookRepository。当然,也应该开发NHibernateRepository。
使用界面可以通过MockObjects实现出色的单元测试。您只需要实现MockBookRepository并在注入时使用它。有很多Mock框架可以帮助你 - 例如Moq。
您可以动态切换存储库而无需更改代码。例如,如果您的数据库是临时关闭的,但是您有另一个可以处理新订单的例子,因为它们是关键的(坏的例子,我知道)。在这种情况下,您会检测到数据库崩溃,并执行以下操作:
currentRepository = temporaryOrdersOnlyRepository;
现在你的代码继续运行,除了你的get data和delete方法返回异常,但CreateNewOrder()方法会将命令保存到字符串文件中)
祝你好运!答案 1 :(得分:2)
这是一项服务
public interface IFoodEstablishmentService
{
Task<int> AddAsync(FoodEstablishment oFoodEstablishment);
Task<int> UpdateAsync(FoodEstablishment oFoodEstablishment);
}
这是我的正常实施
public class FoodEstablishmentService : IFoodEstablishmentService
{
public async Task<int> AddAsync(FoodEstablishment oFoodEstablishment)
{
// Insert Operation
return result;
}
public async Task<int> UpdateAsync(FoodEstablishment oFoodEstablishment)
{
// Update Logic
return result;
}
}
这就是我使用它的方式
IFoodEstablishmentService oFoodEstablishmentService = new FoodEstablishmentService();
oFoodEstablishmentService.AddAsync(oFoodEstablishment);
但是如果我需要通过队列而不是直接向服务器传递插入逻辑,等待插入操作完成然后返回结果,而不是传递队列然后队列工作者处理那些操作呢? 因此,我只是实现了另一个具有相同接口的类
,而不是搞乱一切public class FoodEstablishmentQueueService : IFoodEstablishmentService
{
public async Task<int> AddAsync(FoodEstablishment oFoodEstablishment)
{
// Insert Queue Operation
return result;
}
public async Task<int> UpdateAsync(FoodEstablishment oFoodEstablishment)
{
// Update Queue Logic
return result;
}
}
这就是我使用它的方式,如果不破坏任何东西就不容易,而且如前面的回答所说的DI容器效果更好
IFoodEstablishmentService oFoodEstablishmentService = new FoodEstablishmentQueueService();
oFoodEstablishmentService.AddAsync(oFoodEstablishment);
我想不要选择最好的模式而不是从任何开始,然后慢慢地你将需要更多的东西然后模式发挥另外存储库模式或通用存储库模式可能不是大规模应用程序的理想模式选择逻辑不仅仅是选择模型数据。请搜索CQRS模式。