Skip to content

Exploding Sdk imports

Kirill Osenkov edited this page Apr 15, 2021 · 1 revision

Sometimes you want to add logic to a project after the Sdk.targets is imported. But Sdk.targets is imported at the very end of the project automatically, there seems to be no way to insert anything after the end?

There are two ways actually. Logic placed in Directory.Build.targets runs very late, almost at the very end.

But if you need to have the logic in the project itself, not in Directory.Build.targets, you need to "explode" the Sdk imports, which is, specify them manually.

Instead of

<Project Sdk="Microsoft.NET.Sdk">
  ...
</Project>

you write

<Project>
  <Import Project="Sdk.props" Sdk="Microsoft.NET.Sdk" />
  ...
  <Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" />
  <!-- this is the very end, write your logic here -->
</Project>

So you can add stuff after Sdk.targets

Hint: in the binlog viewer, right-click on a project and choose Preprocess to view the file as MSBuild sees it, with all imports inlined in order. This file shows the actual order of MSBuild evaluation top to bottom, so things that appear earlier in the file will be evaluated first. Search for your logic in this file to determine ordering.