我正在将我们旧的基于Active-Record的API移植到新的结构中,以便更容易进行单元测试等。我们使用存储库模式来访问数据,并使用StructureMap进行依赖注入。
现在我有些困惑如何组织所有内容。以我们的“Product”类为例,以前我们的模型、存储库和工厂部分都建立在产品对象中,例如,要加载、编辑和保存一个产品,我们可以这样做(简化版):
然而,Product类具有加载相关数据的能力,例如:
现在我有些困惑如何组织所有内容。以我们的“Product”类为例,以前我们的模型、存储库和工厂部分都建立在产品对象中,例如,要加载、编辑和保存一个产品,我们可以这样做(简化版):
Dim p As New Product
If(p.Load(1))
p.Name = "New Name"
p.Save()
End If
为了获得对象集合,我们在对象上有一个共享(静态)方法,作为基本的工厂。
Dim arrProds = Product.GetProducts()
在查看了一些例子后,我们的新结构中现在有一个IProductRepository、一个IProductService(它是工厂)和一个Product模型类。因此,代码大致如下:
Dim prodSvc = ObjectFactory.GetInstance(Of IProductService)
Dim prod = prodSvc.GetProduct(1) //Prod is an Instance of 'Product'
prod.Name = "New Name"
prodSvc.Save(prod)
然而,Product类具有加载相关数据的能力,例如:
Dim arrRelatedProds = prod.RelatedProducts
在Product类中,它看起来像这样
Class Product
Function RelatedProducts() As IList(Of Product)
// prodSvc is an instance of IProductService which is passed into the
// Product class in the constructor (or via Dependency Injection)
Return Me.prodSvc.GetRelatedProducts(Me.ProductID)
End Function
End Class
我不喜欢这个因为它很难测试,而且我不喜欢我的“模型”类(产品)直接调用IProductService类。
有没有人对更好的组织结构有建议?
谢谢
詹姆斯
编辑 可能问这个问题的时间不对!是否有任何澄清可以增加以使此问题可回答?