Do you have some sort of ImmutableAttribute in your domain that you use to mark classes as immutable? Have you ever needed to enforce that contract? Checking for readonly fields isn’t enough? Well, this weekend I had a code spike that helped solve this problem in my current project. For this project, I’m using the NoRM driver for MongoDB, and one of the limitations of the serializer is that all types must be classes, must have a default constructor, and all properties have a public setter. So, now the domain has a bunch of classes like this: public class UserCreatedEvent : IEvent { public string Name { get; set; } public UserCreatedEvent() { } public UserCreatedEvent(string name) { Name = name; } } That God for code snippets (or Resharper templates). With so many classes like this that need to get serialized, I wanted to extra sure that no code ever calls the setter method for the Name property. Thankfully, with some help of Mono.Cecil, it’s possible.
Read on...