当创建一个仓库类时,例如CustomerRepository,我的方法应该是静态的吗?
还是我应该首先实例化CustomerRepository类,然后在实例上调用公共方法?
哪种方法最好,为什么?
谢谢
还是我应该首先实例化CustomerRepository类,然后在实例上调用公共方法?
哪种方法最好,为什么?
谢谢
针对单元测试,我会选择使用一个实例(instance)
,因为静态(static)
方法对于模拟(mocking)来说相对困难。
静态(static)
方法会导致测试的可测试性受到极大的影响,因此应该尽可能避免使用。
静态方法很难测试,但同时也更容易调用,所有操作都可以在一个方法中完成,而不是启动存储库、调用其方法和关闭存储库。有多种实现方式,我们发现以下方式最好,因为您无法覆盖静态方法,因此如果将来想要继承和扩展功能,这会有一点困难。
我们另一种方法是,我们具有实例方法,但我们有一个静态变量..例如...
CustomerRepository.Repository.GetAll();
这就是它的实现方式...
class CustomerRepository{
// Only one static variable
public static CustomerRepository Repository = new CustomerRepository();
// all methods are instance methods..
public IEnumerable GetAll(){
...
}
}