Create a message contract
Create an assembly
Section titled “Create an assembly”Create a new project, using the class library template.
dotnet new classlib -o ./src/MyProject.Contractsdotnet sln add ./src/MyProject.ContractsAdd message contract
Section titled “Add message contract”The message examples below show the same command to update a customer address using each of the supported contract types. Messages must be public reference types and can be defined using records, interfaces, or classes.
While non-public message types are allowed, they might be created using temporary broker entities where supported and may cause developer confusion.
Using a record
Section titled “Using a record”namespace Company.Application.Contracts{ using System;
public record UpdateCustomerAddress { public Guid CommandId { get; init; } public DateTime Timestamp { get; init; } public string CustomerId { get; init; } public string HouseNumber { get; init; } public string Street { get; init; } public string City { get; init; } public string State { get; init; } public string PostalCode { get; init; } }}Using an interface
Section titled “Using an interface”namespace Company.Application.Contracts{ using System;
public interface UpdateCustomerAddress { Guid CommandId { get; } DateTime Timestamp { get; } string CustomerId { get; } string HouseNumber { get; } string Street { get; } string City { get; } string State { get; } string PostalCode { get; } }}When defining a message type using an interface, MassTransit will create a dynamic class implementing the interface for serialization, allowing the interface with get-only properties to be presented to the consumer. To create an interface message, use a message initializer.
Using a class
Section titled “Using a class”namespace Company.Application.Contracts{ using System;
public class UpdateCustomerAddress { public Guid CommandId { get; set; } public DateTime Timestamp { get; set; } public string CustomerId { get; set; } public string HouseNumber { get; set; } public string Street { get; set; } public string City { get; set; } public string State { get; set; } public string PostalCode { get; set; } }}Properties with
private set;are not recommended as they are not serialized by default when usingSystem.Text.Json.
Customize using attributes
Section titled “Customize using attributes”| Attribute | Description |
|---|---|
| EntityName | The exchange or topic name |
| ExcludeFromTopology | Don’t create an exchange or topic unless it is directly consumed or published |
| ExcludeFromImplementedTypes | Don’t create a middleware filter for the message type |
| MessageUrn | The message urn |