Targets, Tasks & Hooks
Evaluation gives MSBuild a set of properties, items and targets. Execution then runs targets. A target is a named list of tasks (small compiled units of work: Message, Copy, Exec, Csc, WriteLinesToFile…) plus rules about what must run before and after it. dotnet build asks for the target Build; dotnet pack asks for Pack; dotnet msbuild -t:Name asks for any target you like.
Ordering: DependsOnTargets, BeforeTargets, AfterTargets
mkdir order && cd order
cat > order.proj <<'XML'
<Project>
<Target Name="Restore">
<Message Importance="high" Text="Restore" />
</Target>
<Target Name="Compile" DependsOnTargets="Restore">
<Message Importance="high" Text="Compile" />
</Target>
<Target Name="Test" DependsOnTargets="Compile;Restore">
<Message Importance="high" Text="Test" />
</Target>
<Target Name="Lint" BeforeTargets="Compile">
<Message Importance="high" Text="Lint (hooked before Compile)" />
</Target>
<Target Name="Report" AfterTargets="Test">
<Message Importance="high" Text="Report (hooked after Test)" />
</Target>
</Project>
XML
dotnet msbuild -nologo -v:m -t:Test
echo "--- two targets on the command line"
dotnet msbuild -nologo -v:m -t:Compile -t:Report Restore
Lint (hooked before Compile)
Compile
Test
Report (hooked after Test)
--- two targets on the command line
Restore
Lint (hooked before Compile)
Compile
Report (hooked after Test)
The rules, all visible above:
DependsOnTargetslists targets that must run before this one. They run in order, and they run first, even beforeBeforeTargetshooks.BeforeTargets="X"/AfterTargets="X"attach your target to someone else's, without changing their definition. This is how you extend the SDK: you can't editSdk.targets, but you can hook into any target it defines.- Every target runs at most once per build.
Restoreis a dependency of bothCompileandTest, yet it ran once. That's why the second command printed onlyReportfor the second target:Compileand its hooks were done. - Asking for
Reportdirectly ran it, even though it's normally a hook. Hooks are just targets.
Hooking into the SDK's build
The SDK's Build target is defined roughly as DependsOnTargets="BeforeBuild;CoreBuild;AfterBuild", and CoreBuild depends on a long chain: ResolveReferences, CoreCompile (the C# compiler), CopyFilesToOutputDirectory and dozens more. You pick the hook point by what your step needs:
mkdir hooks && cd hooks
cat > hooks.csproj <<'XML'
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
</PropertyGroup>
<Target Name="PrintVersionInfo" BeforeTargets="CoreCompile">
<Message Importance="high" Text="[before compile] $(AssemblyName) $(Version) for $(TargetFramework)" />
</Target>
<Target Name="AfterBuildStep" AfterTargets="Build">
<Message Importance="high" Text="[after build] output is $(TargetPath)" />
</Target>
<Target Name="ListOutput" AfterTargets="Build">
<Exec Command="ls $(OutDir)" />
</Target>
</Project>
XML
echo 'public class Lib {}' > Lib.cs
dotnet build -nologo -p:Version=1.4.0 Determining projects to restore...
Restored /home/learner/hooks/hooks.csproj (in 58 ms).
[before compile] hooks 1.4.0 for net10.0
hooks -> /home/learner/hooks/bin/Debug/net10.0/hooks.dll
[after build] output is /home/learner/hooks/bin/Debug/net10.0/hooks.dll
hooks.deps.json
hooks.dll
hooks.pdb
Build succeeded.
0 Warning(s)
0 Error(s)
Time Elapsed 00:00:02.36
[before compile]printed before thehooks -> …line:CoreCompileruns before the copy tobin/.- Both
AfterTargets="Build"hooks ran after the output existed, in the order they appear in the file.Execruns a shell command (/bin/shon Linux,cmd.exeon Windows, so keep commands portable or condition them on$(OS)). $(TargetPath)and$(OutDir)are SDK properties computed during evaluation; you can use them in any target.
Note: Older docs suggest overriding the empty
BeforeBuildandAfterBuildtargets. In an SDK-style project that silently fails, becauseSdk.targetsis imported after your project body and redefines them as empty. UseBeforeTargets/AfterTargetswith your own target names instead.
Failing a build on purpose
The Error and Warning tasks print MSBuild diagnostics with a code, which IDEs and CI systems pick up like compiler errors:
mkdir guard && cd guard
cat > guard.csproj <<'XML'
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
</PropertyGroup>
<Target Name="ReleaseGuard" BeforeTargets="CoreCompile" Condition="'$(Configuration)' == 'Release'">
<Warning Code="ADA001" Text="No release notes for $(Version)." Condition="!Exists('RELEASE-NOTES.md')" />
<Error Code="ADA002" Text="Pass -p:ReleaseTicket=... for a release build." Condition="'$(ReleaseTicket)' == ''" />
</Target>
</Project>
XML
echo 'public class Lib {}' > Lib.cs
dotnet build -nologo -v:q -c Release
echo "exit code: $?"
dotnet build -nologo -v:q -c Release -p:ReleaseTicket=REL-42 | grep -E 'ADA|Warn|Err'/home/learner/guard/guard.csproj(6,5): warning ADA001: No release notes for 1.0.0.
/home/learner/guard/guard.csproj(7,5): error ADA002: Pass -p:ReleaseTicket=... for a release build.
Build FAILED.
/home/learner/guard/guard.csproj(6,5): warning ADA001: No release notes for 1.0.0.
/home/learner/guard/guard.csproj(7,5): error ADA002: Pass -p:ReleaseTicket=... for a release build.
1 Warning(s)
1 Error(s)
Time Elapsed 00:00:00.92
exit code: 1
/home/learner/guard/guard.csproj(6,5): warning ADA001: No release notes for 1.0.0.
/home/learner/guard/guard.csproj(6,5): warning ADA001: No release notes for 1.0.0.
1 Warning(s)
0 Error(s)
The guard hooks CoreCompile, not Build, so a release build fails before the compiler runs rather than after all the work is done. The failing build exits with code 1, which is what CI looks at. (Don't guard on properties like Company or Authors: the SDK defaults both to the assembly name, so they are never empty.) Codes like ADA001 can be suppressed or promoted per project (<NoWarn>, <WarningsAsErrors>), exactly like compiler warnings.
Test yourself
Target T has DependsOnTargets="A", and target H has BeforeTargets="T". In which order do they run when you build T?
- H, A, T
- A, H, T
- T, A, H
- A, T, H
Two targets both depend on Restore. How many times does Restore run in one build?
- Once
- Twice
- Once per project file import
- It depends on -v
Why doesn't <Target Name="AfterBuild"> work reliably in an SDK-style project?
- AfterBuild was removed from MSBuild
- Sdk.targets is imported after the project body and redefines AfterBuild, replacing yours
- It needs a Condition
- It only runs in Release