Skip to content

Create a message contract

Create a new project, using the class library template.

Terminal window
dotnet new classlib -o ./src/MyProject.Contracts
dotnet sln add ./src/MyProject.Contracts

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.

./src/MyProject.Contracts/UpdateCustomerAddress.cs
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; }
}
}
./src/MyProject.Contracts/UpdateCustomerAddress.cs
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.

./src/MyProject.Contracts/UpdateCustomerAddress.cs
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 using System.Text.Json.

AttributeDescription
EntityNameThe exchange or topic name
ExcludeFromTopologyDon’t create an exchange or topic unless it is directly consumed or published
ExcludeFromImplementedTypesDon’t create a middleware filter for the message type
MessageUrnThe message urn