领域对象封装:静态方法与服务类

发布于 2024-10-14 08:07:32 字数 358 浏览 3 评论 0原文

我在 DDD 书(Eric Evans)中读到,需要在演示中使用的过程应该移至服务类。例如,BankAccountManagementService 有 ChangeBankAccount、GetByAccountId ... 方法。

但是,我需要封装某些属性的设置器,以禁止从其他业务对象分配它们。由于 C# 没有友好的类,因此在服务中不可能使用这种类型的封装。但可以使用 BankAccount 业务对象的静态方法来完成此操作。

(1)因上述原因使用服务时,您如何解决此限制?

编辑:附加问题

(2)为什么使用静态方法而不是服务不好?我可以将它们放在单独的部分类文件中,以免将过程代码与实体代码混合。

提前致谢 :)

I've read in DDD book (Eric Evans) that procedures which require to be used in presentation should be moved to services classes. For instance BankAccountManagementService has ChangeBankAccount, GetByAccountId ... methods.

However I need to encapsulate setters of some properties to forbid assigning them from other business objects. As C# doesn't have friendly classes it is impossible to use this type of encapsulation in case of Services. But it is possible to do it using static methods of BankAccount business object.

(1) How do you solve this limitation in case of using Services for mentioned above reason?

Edit: additional question

(2) Why it is bad to use static method instead of services? I can place them in separate partial class file to not mix proc code with Entity code.

Thanks in advance :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

檐上三寸雪 2024-10-21 08:07:32

如果不应设置域对象的属性(不可变),则将它们设置为私有(或受保护)。

负责更改域对象的私有属性的服务方法将执行必要的验证和/或权限检查,并通过其构造函数之一(包括其 id)使用它想要更改的属性创建一个新对象并保存该对象。

另一种选择是在域对象上放置一个 set 方法,该方法采用新值和某种权限对象,或者将该方法归因于需要某些权限。这样你就可以限制集合的调用位置。

编辑:
使事物静态化是一个架构黑洞:
你不能继承它们或以任何方式改变它们。
它使得无法使用依赖注入。
版本控制更加困难;一旦你做出了静态并被使用,就很难改变这个决定。
此外,您的静态方法现在可能不使用实例数据,但将来可能需要。

当方法是实例方法时,您可以利用多态性和泛型,创建泛型 ServiceBase 类并将常用方法放在那里。

If properties of a domain object should not be set (immutable), then make them private (or protected).

The service method that is responsible for altering the private properties of a domain object would perform necessary validation and or permissions checks and create a new object via one of its constructors (including its id) with the properties it wants to change and save that object.

Another option would be to put a set method on your domain object which takes the new value, and some kind of permission object, or attribute the method to require certain privileges. That way you can constrain where the set is called from.

EDIT:
Making things static is an architectural black hole:
You cant inherit from them or alter them in any way.
It makes it impossible to use dependency injection.
Versioning is harder; once you have made then static and the are used, it is hard to reverse that decision.
Also, your static method may not use instance data today, but it may need to in the future.

When the methods are instance methods, you can make use of polymorphism and generics, creating a generic ServiceBase class and putting commonly used methods there.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文