So far I always used an interface for my message contracts:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface UserRegistered{ | |
Guid UserId{get;} | |
} |
In combination with anonymous types, you don’t even need to implement this interface yourself but create an anonymous type on the fly that will be published:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bus.Publish<UserRegistered>(new { UserId = Guid.NewGuid() }); |
Let’s see if we can do the same thing by using a record type instead. Here is our rewritten message contract:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public record UserRegistered{ | |
public Guid UserId { get; init; } | |
} |
We could publish the message in the same way as before:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bus.Publish<UserRegistered>(new { UserId = Guid.NewGuid() }); |
BUT you can also take advantage of the "target-typing" feature in C# 9, this allows us to create a specific instance of the record type instead of an anonymous type:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bus.Publish<UserRegistered>(new() { UserId=Guid.NewGuid() }); |
Did you notice the difference? We call the constructor of the record type through the 'new ()' syntax.