值对象即服务调用参数 [英] Value Object as a Service Call Argument

查看:68
本文介绍了值对象即服务调用参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在《实施DDD》一书中,提到了创建 TenantId 值对象。这对我来说很有意义,因为 GUID 可能为空,这不是有效的 TenantId ,因此,通过我可以保护 TenantId 值对象(我也有其他值对象,例如 Name 电话号码电子邮件地址等):

In the book Implementing DDD, there's mention of creating a TenantId value object. This makes sense to me, as a GUID could be empty which isn't a valid TenantId, so by making a TenantId value object I can protect against this (I also have other value objects like Name, PhoneNumber, EmailAddress, etc):

public class TenantId
{
    public TenantId(Guid id)
    {
        this.SetId(id);
    }

    public Guid Id { get; private set; }

    private void SetId(Guid id)
    {
        if (id == Guid.Empty)
        {
            throw new InvalidOperationException("Id must not be an empty GUID.");
        }

        this.Id = id;
    }
}

我感兴趣的是,我应该还是应该不要在服务方法上使用此 TenantId ,例如:

What I'm interested in, is should I, or should I not, use this TenantId on a service method, something like:

TenantId tenantId = new TenantId(model.TenantId); // model.TenantId being a GUID.

this.tenantService.GetTenant(tenantId);

还是应该在服务方法参数中使用更原始的形式:

Or should I use the more raw form in the service method arguments:

this.tenantService.GetTenant(model.TenantId); // again model.TenantId is a GUID.

这本书似乎有时以一种方式,有时以另一种方式来做。人们对这些方法的利弊有何看法?

The book seems to sometimes do it one way and sometime another. What thoughts do people have on the pros and cons of these approaches?

推荐答案

如果该服务不需要限制访问实体,请传递值对象,因为它是共享标识符,但是我会编写代码

If the service doesn't require restricted access to the entity, pass the value object since it is a shared identifier, but I would code it something like this:

public class TenantId : IEquatable<TentantId>
{
    public TenantId(Guid id)
    {
        if (id == Guid.Empty)
        {
            throw new InvalidOperationException("TenantId must not be an empty GUID.");
        }
        _id = id;
    }

    private readonly Guid _id;

    public Equals(TentantId other)
    {
        if (null == other) return false;
        return _id.Equals(other._id);
    }

    public GetHashcode()
    {
        return _id.GetHashcode();
    }

    public override Equals(object other)
    {
        return Equals(other as TenantId);
    }

    public ToString()
    {
        return _id.ToString();
    }
}

但是在某些情况下,应调用域服务仅对于用户可以在存储库中访问的实体:在这种情况下,域服务的公共接口需要该实体(即使实现仅使用标识符)。

However in some cases, a domain service should be invoked only with entities that the user can access in the repository: in those cases, the public interface of the domain service require the entity (even if the implementation just use the identifier).

这篇关于值对象即服务调用参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆