Search code examples
.netasp.net-coremsbuildpublishpreprocessor-directive

How to pass preprocessor directive to MSBuild via dotnet publish


I have an ASP.NET Core 6.0 WebApi solution with SPA. The default template builds the SPA by default by running PublishAngular target below.

WebApi.csproj file:

<Project Sdk="Microsoft.NET.Sdk.Web">
   <!-- ... -->
   <!-- .NET Core Web API is being build here-->
   <!-- ... -->
   <Target Name="PublishAngular" AfterTargets="ComputeFilesToPublish">
      <!-- ... -->
      <!-- SPA is getting built here-->
      <!-- ... -->
   </Target>
</Project>

I am migrating the WebApi to Docker, and want to eventually completely split off SPA from it. But it's a lengthy process, so for the time being I want to have a way to specify whether I want to build the SPA conditionally using build command line.

I am using a pre-processor directive called DOCKER_BUILD, so I do something like this in my C# files:

#if !DOCKER_BUILD
   services.ConfigureSpa();
#endif

My questions are:

  1. What's the best way of passing a parameter from the build command line to MSBuild engine to exclude/include the PublishAngular target in csproj file?
  2. Can I re-use the DOCKER_BUILD preprocessor diective to accomplish that?

My build command line looks like this:

dotnet publish -c Release -o out


I tried passing in DOCKER_BUILD as:

dotnet publish -c Release -o out /p:DOCKER_BUILD

and modifying the SPA build target like this:

<Target Name="PublishAngular" AfterTargets="ComputeFilesToPublish" Condition="!DOCKER_BUILD">

but didn't have much success. What am I doing wrong?


Solution

  • Got it working as following. Build command line:

    dotnet msbuild -target:Publish /p:DefineConstants=DOCKER_BUILD

    csproj target condition:

    <Target Name="PublishAngular" AfterTargets="ComputeFilesToPublish" Condition="!$(DefineConstants.Contains('DOCKER'))">

    The DefineConstants parameter also works with code inside C# files so this works as well:

    #if DOCKER_BUILD
       // some docker specific code
    #endif