Can I Pass Compilation Constants to a Project Reference?

Viewed 1760

If I have a <ProjectReference> reference, is there any way to pass a conditional compilation value to that project? Something like this (I know <DefineConstants> doesn't exist like this, it's just to illustrate the need):

<ProjectReference Include="..\DataProducer\DataProducer.csproj">
  <DefineConstants>WAS_SET</DefineConstants>
<ProjectReference>

Therefore, if there's a class in that project like this:

    public sealed class ProduceValue
    {
        public string Produce()
        {
#if WAS_SET
            return "WAS SET";
#else
            return "NOTHING WAS SET";
#endif
        }
    }

Then by passing that value during compilation or not, I could get different output.

2 Answers

I think the possible soution is "Targets" of "ProjectReference" https://github.com/dotnet/msbuild/blob/master/src/MSBuild/MSBuild/Microsoft.Build.CommonTypes.xsd#L644

define a target in DataProducer.csproj. define the Constants property in the target. thus make the target before build target.

then it should works?

Update:

tried my prev option, it doesn't works. another option:

  1. copy DataProducer.csproj and rename to DataProducer.WAS_SET.csproj
  2. add DefineConstants for DataProducer.WAS_SET.csproj
  3. update ProjectReference Include="..\DataProducer\DataProducer.WAS_SET.csproj"

so DataProducer.csproj & DataProducer.WAS_SET.csproj will share the code. and we could refer to any one we want.

and we could use different AssemblyName for that two csproj. thus same source code, but different dll.

Related