As far as I know, at the moment we can call other targets from within a target by using the attribute DependsOnTargets
or by using the task <CallTar开发者_运维知识库get ...>
My question is when should we use each case?
MSBuild provides different ways to call target :
- MSBuild task
- CallTarget task
- DependsOnTarget target attribute
- BeforeTargets and AfterTargets target attributes in MSBuild 4
Using CallTarget
is an explicit approach, you start at your first target and call explicitly each target in the order you want.
Whereas DependsOnTargets
is an implicit approach, MSBuild infers the calling order by checking the dependency of the targets.
There is no difference between CallTarget
and DependsOnTargets
on the number of time a target could run : a target will never run twice during a single build (except if you use MSBuild task with different property)
Limitation of CallTarget
One limitation of CallTarget
is with dynamic items and property : you can't access an item or a property that you have created in a target in another target called with CallTarget :
<Target Name="Caller">
<CreateProperty Value="MyValue">
<OutputTaskParameter="Value" PropertyName="NewProperty"/>
</CreateProperty>
<CallTarget Targets="Called"/>
</Target>
<Target Name="Called">
<Message Text="$(NewProperty)"/>
</Target>
Dynamic property aren't publish until the target that created them is done executing. You don't have this problem using DependsOnTarget
What should I use?
You should use DependsOnTargets
for targets that need to be executed before your target. And CallTarget
for target to execute after your target. That's the way Microsoft do it.
<Target Name="CoreCompile"
DependsOnTargets="$(CoreCompileDependsOn)">
<!-- Target execution -->
<Csc ... />
...
<!-- Targets to execute after -->
<CallTarget Targets="$(TargetsTriggeredByCompilation)"/>
</Target>
The critical difference is that a target specified in DependsOnTarget will not execute if it has already executed previously. In this way, multiple targets can then have the same dependency, but only the first target will trigger its execution (see MSDN documentation).
You can think of it as saying "Make sure this target has already executed, and execute it if it hasn't."
CallTarget will just simply execute the target specified, regardless of whether it has executed previously or not.
精彩评论