dotnet / msbuild

The Microsoft Build Engine (MSBuild) is the build platform for .NET and Visual Studio.
https://docs.microsoft.com/visualstudio/msbuild/msbuild
MIT License
5.23k stars 1.35k forks source link

No way to run NuGet package's task only once after build #4933

Closed JVimes closed 4 years ago

JVimes commented 4 years ago

I need a task that:

The following works in the .csproj, or a .targets file directly imported by the .csproj. But it does not run in a .targets file brought in by a NuGet package.

<Target Name="RunMyScript" AfterTargets="Build" Condition=" '$(IsCrossTargetingBuild)' == 'true' ">
    <Message Text="===== RunMyScript has been called! =====" Importance="High" />
</Target>

Here's a stripped down version of my project:

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
    <PropertyGroup>
        <OutputType>Library</OutputType>
        <TargetFrameworks>netcoreapp3.0;net462;net48</TargetFrameworks>
        <UseWPF>true</UseWPF>
        <Version>8.6.9</Version>
    </PropertyGroup>
    <ItemGroup>
        <PackageReference Include="MyNuGetPackage" Version="2.2.2">
            <PrivateAssets>all</PrivateAssets>
            <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
        </PackageReference>
    </ItemGroup>
</Project>

Is there a way?

JVimes commented 4 years ago

@dasMulli I tried your suggestion (thanks!) and made my nuget package put my targets file in Sdk\Sdk.targets (I don't have a props file). But the target doesn't run, even without conditions. The .csproj looks the same as before. The docs don't look like what I'm doing, to my eye. Any ideas? 🤔

dasMulli commented 4 years ago

I think you’ll need a props file as well and then you don’t reference the package via NuGet (package reference) but extend the Sdk Attribute in your project to e.g "Microsoft.NET.Sdk;My.Package/1.2.3"

Maybe a full example helps..

JVimes commented 4 years ago

Thanks, I wish that were acceptable but it sounds like it requires editing every .csproj by hand? Until multi-framework projects arrived, my coworkers just installed my NuGet package and it "just worked".

dasMulli commented 4 years ago

You can also create a Directory.Build.props file in your solution directory and put in:

<Project>
  <Import Project="Sdk.targets" Sdk="Your.Pkg/1.2.3" />
</Project>

This file will be auto imported into every capris file in the hierarchy automatically.

JVimes commented 4 years ago

The .csproj files are in different products (different codebases) and only select projects need the task. I can't think of a practical way to make use of Directory.Build.props. I appreciate the suggestions.

rainersigwald commented 4 years ago

Duplicate of #2540