Nat*_*lor 6 design-patterns repository-pattern
在实现存储库模式的ASP.NET MVC应用程序中,我很好奇是否适合将非数据相关方法放在存储库中,如果它们仍然属于给定存储库的一般焦点.例如,假设一个ProductsRepository具有添加和删除ProductImages的方法,这些方法在数据库和本地文件存储中也有部分表示.如果需要删除ProductImage,我们需要使用存储库方法从数据库中删除一行,并且还需要从存储介质中删除与该映像关联的文件.IO操作是否属于存储库,还是有更合适的位置?
我在我刚刚描述的情况下做的一件事就是在我的存储库中提供静态方法,它通过使用存储在数据库中的文件名和预定义的目录模式为我提供给定ProductImage的路径,以编程方式生成它.这是否超出了存储库的预期用途?
编辑
如果这样的操作不属于存储库,那么类似的东西应该放在MVC模式中?在我看来,在Controller和Repository之间有另一层可以根据需要调用Repository并且可以从Controller静态调用它.
我认为对存储库模式更大的担忧是您违反了单一职责原则。您的类应该承担一项职责,例如操作数据库中的数据。您应该有一个不同的类来处理文件 IO,并且您可以将函数分组到一个类中的上一层。
类的更改应该只有一个原因,而处理文件 IO 和数据库调用的存储库类将有两个原因。文件系统布局的更改或数据库的更改。
为了解决您的编辑问题,以下是我在 MVC 场景中实现这一点的方法(这也假设您正在使用某种依赖注入来使生活更轻松)。
// Controller class
public class ProductsController
{
private IProductService _productService;
public ProductsController(IProductService productService)
{
_productService = productService
}
public void RemoveImage(int productId, int imageId)
{
_productService.RemoveImage(productId, imageId)
}
}
public class ProductService: IProductService
{
private IProductRepository _productRepository;
private IProductImageManager _imageManager;
public ProductService(IProductRepository productRepository, IProductImageManager imageManager)
{
_productRepository = productRepository;
_imageManager = imageManager;
}
public void RemoveImage(int productId, int imageId)
{
// assume some details about locating the image are in the data store
var details = _productRepository.GetProductImageDetails(productId, imageId);
// TODO: error handling, when not found?
_imageManager.DeleteImage(details.location);
_productRepository.DeleteImage(productId, imageId)
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以根据任何有意义的接口来实现 IProductImageManager 和 IProductRepository,并根据您的特定需求进行具体实现。