I blogged about fluent interfaces and expression builders a couple of times before. For this post, I want to share a base class that I've been using for taking away some of the burden when creating expression builders for domain classes.
Here's the expression I'm after:
This creates an instance of a domain class named Document with the name of the author, its title and with an associated tag. Let me first show the code of the expression builders that make this happen.
The expression builders all provide progressive interfaces. Also notice that the DocumentBuilder derives from a base class named Builder. This class provides a method ProvideValueFor that is used to feed the base class with the name of a property and a corresponding value. Collections are also supported. Here's the code for the Builder class.
var document = DocumentBuilder.BuildDocument()
.AuthoredBy("Stephen Hawking")
.Titled("The Universe in a Nutshell")
.TaggedWith(tag => tag.Named("Physics"))
.Build();
Using this approach, its no longer necessary to make any compromise of exposing property setters or a dedicated constructor just for serving the expression builders. The Builder class uses refection to set the value of a property or to fill a collection. The BackingFieldResolver is a class I picked up from this post. Very cool stuff!
I have only used this approach in a couple of side projects, but let me know you think.
Till next time.