user630190
user630190

Reputation: 1162

Inherit Parent MsBuild file

I have a project structure that looks like this:

Parent -- ChildProjects1 -- ChildProjects2 -- ChildProjects3

I have an msbuild file under each ChildProjects node that builds the relevant projects, creates zip files, tags them in subversion etc

However most of this logic is common between ChildProjects. I'm wondering if I can refactor this common logic to sit in another msbuild file at the parent level and have each child inherit this?

Any ideas on this appreciated.

Upvotes: 3

Views: 1180

Answers (1)

Bronumski
Bronumski

Reputation: 14272

You can put common Targets inside an a file that you include using the following syntax, you will also see it in your proj files:

<Import Project="path to file.targets"/>

Things to note:

  • The convention is to use a .targets extension but it doesn't matter.
  • Where you place the import is important depending on if you want to be able to override properties or targets in the imported targets file.
  • Targets are not like methods, you cannot call them more than once but you can influence the order in which they are called.
  • If you require reusable chunks that you want to call multiple times create a custom task library but check out the MSBuildExtensionPack first to see if it has what you want.

Call Target

In relation to the question about CallTarget. CallTarget will invoke the specified target(s) the same way that DependsOnTargets, BeforeTargets and AfterTargets do. The target will only be run if it has not already been run. See the following example:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Foo">

  <Target Name="Foo" DependsOnTargets="Bar"> 
    <Message Text="Foo" />
    <CallTarget Targets="Bar" />
    <CallTarget Targets="Bar" />
  </Target>

  <Target Name="Bar" AfterTargets="Foo" BeforeTargets="Foo">
    <Message Text="Bar" />
  </Target>

</Project>

Which will output the following:

Microsoft (R) Build Engine version 4.0.30319.17929
[Microsoft .NET Framework, version 4.0.30319.18449]
Copyright (C) Microsoft Corporation. All rights reserved.

Build started 24/02/2014 12:06:59.
Project "D:\Dev\Test.proj" on node 1 (default targets).
Bar:
  Bar
Foo:
  Foo
Done Building Project "D:\Dev\Test.proj" (default targets).


Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:00.69

Upvotes: 4

Related Questions