Lessons in MSBuild - Applying the Single Responsibility Principle

As an experienced developer, I promote the use of good practices in object-oriented designs.

I was modifying a number of MSBuild and TFS Build project files for several related environments and I noticed that they both duplicated information and each had more than one responsibility - such as specifying the solution to build and compilation settings such as code analysis, configuring testing, and then perhaps performing some custom operations.

I wondered if I could apply the Single Responsibility Principle to the build project files.

Indeed, you can split your project files into multiple files, and from the main project you can import the other file by using the following syntax.

1<Import Project="MyCommonTargets.proj" />

Lessons In MSBuild - Targets Are Called Only Once

By design, targets in a MSBuild process are only called once. This is an important concept to understand, as it is unusual for the typical developer.

I had a situation where I wanted to call the same target from a few places in my MSBuild project - but I wanted to pass in different property values. I didn’t want to repeat myself (DRY principle).

If <CallTarget ...> is used then the target is only called once within that process.

I found a sneaky way to work around this by examining the file C:\Program Files\MSBuild\Microsoft\VisualStudio\TeamBuild\Microsoft.TeamFoundation.Build.targets.

Instead of using <CallTarget ...>, use <MSBuild ...> which spawns off a new MSBuild process, thus allowing the target to be called each time.

1<MSBuild Projects="$(MSBuildProjectFile)" Targets="MyTarget" Properties="MyProperty1=blah;MyProperty2=$(MyVariable)\blah2" />

Lessons in MSBuild - Introduction

The Microsoft build engine (MSBuild) is not necessarily the easiest to learn, and documentation and examples can be difficult to find.

There is however an excellent book written by Sayed Ibrahim Hashimi and William Bartholomew titled “Inside the Microsoft Build Engine: Using MSBuild and Team Foundation Build” (Microsoft Press, 2009, ISBN-13: 978-0-7356-2628-7). I very strongly recommend purchasing this book if you are serious about learning MSBuild.

In this series of lessons I will be discussing a few MSBuild related tips that I found useful to understand during my recent dabbling in MSBuild 3.5 projects.