DDD 存储库
创建存储库类时,例如。 CustomerRepository,我的方法应该是静态的吗?
或者我应该首先实例化 CustomerRepository 类,然后调用该实例的公共方法?
哪种方法最好,为什么?
谢谢
When creating a repository class, eg. CustomerRepository, should my methods be static?
Or should I first instanciate the CustomerRepository class, and then call the public methods on the instance?
Which approach is best and why?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会使用一个
实例
来进行单元测试 - 例如,使用静态
方法进行模拟是很困难的。静态
方法是死亡可测试性。I'd go with an
instance
simply for unit testing - mocking for example is hard with astatic
method.Static
methods are death to testability.我总是创建一个描述我的存储库合同的界面。
因此,我不会走静态成员的路线。
不仅是为了已经提到的可测试性,还因为我的存储库需要有一个“上下文”。
更具体地说,我使用 NHibernate 作为 OR/M 映射器,并将应该用于存储库实例的 ISession 传递。通过这样做,多个存储库可以使用相同的 ISession (UnitOfWork),因此可以在同一事务中持久保存多种不同的类型。
I always create an interface which describes the contract for my repository.
Thus, I do not go down the route of static members.
Not only for testability which has already been mentionned, but also because of the fact that my repository needs to have a 'context'.
More specifically, I use NHibernate as an OR/M mapper, and I pass the ISession that should be used to the repository instance. By doing so, multiple repositories can use the same ISession (UnitOfWork), and thus, multiple different types can be persisted within the same transaction.
您应该创建一个接口 ICustomerRepository,然后创建一个从该接口派生的类 CustomerRepository。
原因是可测试性。
在测试中,您现在可以使用一些模拟对象模拟 CustomerRepository 的具体实例。
您还可以轻松替换此存储库的实现、添加日志记录或缓存。
至于静力学。如果你想使用静态实例,最好使用一些依赖注入工具并将组件的生活方式设置为单例。它仍然是可测试的。
You should propably create an interface ICustomerRepository, and then create a class CustomerRepository that derives from from that interface.
The reason why is testability.
In tests you can now mock out the concrete instance of CustomerRepositotory with some mock object.
You can also easily replace implementations of this repository, add logging or caching.
As for statics. If you want to use static instance, it's better to use some Dependency Injection tool and set component's lifestyle to singleton. It still would be testable.
静态很难测试,但同时,静态更容易调用,一切都可以归结为一种方法,而不是启动存储库并调用其方法并关闭存储库。实现方法有很多种,我们发现下面的方法是最好的,因为你不能覆盖静态方法,所以以后如果你想继承和扩展功能,有点困难。
我们拥有的另一种方法是,我们有实例方法,但我们有一个静态变量......例如......
这就是它的实现方式......
Statics are hard to test, but at the same time, statics are eaier to call, everything can be brought down to one method instead of initiating repository and calling its method and closing repository. There are various ways to implement it, we have found following way is the best, because you can not override static methods so in future if you want to inherit and extend functionality, its little bit difficult.
Another approach we have is, we have instance method but we have one static variable.. for example...
and this is how its implemented...