bling.github.io

This blog has relocated to bling.github.io.

Sunday, April 17, 2011

Integrating DependencyPropertyWeaver Into Your Build

See the introduction here.

The MSBuild task as it stands currently by default will attempt to weave everything that it finds.  This is probably not optimal in most use cases, but any changes is a simple modification to the LINQ query in the code.  For now, it’s only available in source format since there are bound to be bugs here and there, and once those get ironed out it’ll be easier to release a “point something” release.

An example of how its used can be seen in the unit tests, in the project DependencyPropertyWeaver.Tests.Models.  If you open it up in your favorite text editor, you will see this crucial line:

<Target Name="AfterBuild">
    <Exec Command="C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe postbuild.proj /p:Files=DependencyPropertyWeaver.Tests.Models.dll" WorkingDirectory="$(OutputPath)" />
  </Target>

And the contents of postbuild.proj is simply this:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Weave" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <UsingTask TaskName="DependencyPropertyWeaver.DependencyPropertyWeaverTask"
             AssemblyFile="DependencyPropertyWeaver.dll" />
  <Target Name="Weave">
    <ItemGroup>
      <Input Include="$(Files)" />
    </ItemGroup>
    <DependencyPropertyWeaverTask Files="@(Input)" />
  </Target>
</Project>

The AfterBuild target is a special target with MSBuild, which, as the name implies, will run after the target has been built.  In this case, after the project is completed, it will invoke another MSBuild instance to perform the weaving.  Invoking a new MSBuild process is required because the <UsingTask> will load the assembly into the current AppDomain, and once loaded it cannot be unloaded.

If you don’t mind the unloading part, you can simply add the <UsingTask> directly into the project file and invoked the <DependencyPropertyWeaverTask> there, and avoid the hassle of having a separate file.

Currently, the DependencyPropertyWeaverTask supports the TypePatternMatch and AttributePatternMatch, which as the names imply will use regular expression filtering on type names or properties with the attribute you want to weave.  If these properties are null, they are ignored.

Next on the feature list is weaving attached properties ;-)

No comments: