开发者

When to persist your business entities in your services classes

I have开发者_如何学Python a method in my service where I create some entities, inside the method I call my repository's Add method so that the entities are persisted when I call my save method, should I call my Save method outside the service class or inside the method where I add the entities to the datacontext?


A service class must aspire to be self contained and must take care of calling its own save() method for the repository that it uses. This way, it allows abstraction of the repository from its consumers. What if it chooses to dispense with the repository for instance? If the callee is in charge of doing the save(), then the callee() has to change too. This would result in code brittleness.

Transactions, however, are a different matter.

The service class must participate in a global transaction if one has already been started by the callee. In the absence of a global transaction, the service class must start and end its own transaction. Hence the save() method would actually "commit" only at the end of the transaction whether it was started by the service class itself or by the callee.


I would ask, in response to what do you create some entities? chances are that the only reason is to be persisted eventually. By definition your service class would be a much better place for triggering the persistence process. Entities in your data context should only be concerned with responding to the commands coming from your service.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜