Why interfaces for message contracts are strongly recommended in MassTransit?

Viewed 2789

MassTransit states that we should use interfaces for message contracts :

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.

Source : Docs » Using MassTransit » Creating a message contract

What is downside of using POCO DTOs instead of interfaces, what are the obvious advantages of Interfaces over classes in the context of messaging with MassTransit?

On the other hand NServiceBus is fine with POCO, and sure it makes sense to not use internal classes like domain object, see below.

Source : 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.
3 Answers

I think easier dependency injection and multiple implementations as needed providing unified msgs form across the project but different handling logic as much as required

long story short cleaner code and higher maintainability

Using interfaces can make it easier to work with multiple versions of a message. You can have a two separate interfaces, one for each version, and a POCO object implementing two interfaces.

There is a clear definitition of a contract while retaining the compatibility with older version of a contract.

Use the new interface on the output - the code clearly defines the contract.

Use POCO on the input - keep compatibility with both versions.

Related