Search code examples
msbuildnuget.net-corebuild-tools

Use NuGet build tool packages with ASP.NET Core


NuGet has several packages designed for use at build time. An example is Google.Protobuf.Tools, which contains protoc.exe.

With the .csproj system before .NET Core, you could add Google.Protobuf.Tools, and then use a pre-build event to run ..\Packages\...\protoc ....

With the new .NET Core .csproj system, in some ways it's nicer. For example, the .csproj file is cleaned up, so you can easily hand-add a build target to get incremental builds, like this:

<Target Name="PreBuild" BeforeTargets="PreBuildEvent">
  <CallTarget Targets="DeviceMessages" />
</Target>

<Target Name="DeviceMessages" Inputs="DeviceMessages.proto" Outputs="obj\DeviceMessages.cs">
  <Exec Command="..\Packages\Google.Protobuf.Tools.3.4.0\tools\windows_x64\protoc --proto_path=. --csharp_out=obj DeviceMessages.proto" Outputs="obj\DeviceMessages.cs" />
</Target>

The problem is there is no more Packages folder. In general, that's a good thing. But how can I get the path to just the NuGet build tool package I want, for use in a MSBuild target?


Solution

  • For a ASP.NET Core project you could use the $(NuGetPackageRoot) MSBuild property. This is defined after a restore in the generated obj/ProjectName.csproj.nuget.g.props file.

    Then your Exec would be:

    <Exec Command="$(NuGetPackageRoot)Google.Protobuf.Tools.3.4.0\tools\windows_x64\protoc --proto_path=. --csharp_out=obj DeviceMessages.proto" Outputs="obj\DeviceMessages.cs" />