gpt4 book ai didi

c# - 为什么在 MassTransit 中强烈推荐消息契约接口(interface)?

转载 作者:可可西里 更新时间:2023-11-01 09:16:04 25 4
gpt4 key购买 nike

MassTransit 声明我们应该为消息契约使用接口(interface):

It is strongly suggested to use interfaces for message contracts, based on experience over several years with varying levels of developer experience. MassTransit will create dynamic interface implementations for the messages, ensuring a clean separation of the message contract from the consumer.

来源:文档 » 使用 MassTransit » Creating a message contract

使用 POCO DTO 而不是接口(interface)的缺点是什么?在使用 MassTransit 进行消息传递的上下文中,接口(interface)相对于类的明显优势是什么?

另一方面,NServiceBus 适用于 POCO,确保不使用域对象等内部类是有意义的,请参见下文。

来源:NServiceBus » Messaging » Messages, Events and Commands

When creating messages one should follow the following guidelines:

  • Messages should be simple POCO objects.
  • Messages should be as small as possible.
  • Messages should satisfy a Single Responsibility Principle.
  • Classes used for other purposes (e.g. domain objects, data access objects and UI binding objects) should not be used as messages.

最佳答案

虽然与 MassTransit 没有直接关系,但我会说原因是封装。使用 setter 创建一个简单的 POCO,但将其传递到 promise 仅 getter 的接口(interface)后面,将数据封装在 DTO 中。

public class Program
{
static void Main(string[] args)
{
User user = new User()
{
Username = "user99"
};

Account account = new Account(user);
}
}

public interface IUser
{
string Username { get; }
}

public class User : IUser
{
public string Username { get; set; }
}

public class Account
{
private IUser user;

//Currently used in main
public Account(User user)
{
user.Username = ""; //This is allowed
this.user = user;
}

//But consider this ctor
public Account(IUser user)
{
//user.Username = ""; //Not allowed
this.user = user;
}

...
}

关于c# - 为什么在 MassTransit 中强烈推荐消息契约接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44368550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com