MSBuild. Create EmbeddedResource before build

2020-04-20 23:46发布

问题:

I want to embed local references in the assembly before compiling the main unit. But the written target does not work.

  <Target Name="EmbedLocal" BeforeTargets="CoreCompile">
    <Message Text="Run EmbedLocal for $(MSBuildProjectFullPath)..." Importance="high"/>    
    <ItemGroup>
      <EmbeddedResource Include="@( ReferencePath->WithMetadataValue( 'CopyLocal', 'true' )->Metadata( 'FullPath' ) )"/>
    </ItemGroup>
    <Message Text="Embed local references complete for $(OutputPath)$(TargetFileName)." Importance="high" />
  </Target>

@(EmbeddedResource) at this moment contains valid list of paths.

Update:
Now my import file contains:

<Project ToolsVersion="$(MSBuildToolsVersion)" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <EmbedLocalReferences Condition=" '$(EmbedLocalReferences)' == '' ">True</EmbedLocalReferences>
  </PropertyGroup>

  <Target Name="EmbedLocal" BeforeTargets="ResolveReferences" Condition=" '$(EmbedLocalReferences)' == 'True' ">
    <Message Text="Run EmbedLocal for $(MSBuildProjectFullPath)..." Importance="high"/>
    <ItemGroup>
      <EmbeddedResource Include="@(ReferenceCopyLocalPaths->WithMetadataValue( 'Extension', '.dll' )->Metadata( 'FullPath' ))">
        <LogicalName>%(ReferenceCopyLocalPaths.Filename)%(ReferenceCopyLocalPaths.Extension)</LogicalName>
      </EmbeddedResource>
    </ItemGroup>   
    <Message Text="Embed local references complete for $(OutputPath)$(TargetFileName)." Importance="high" />
  </Target>
</Project>

It works fine. Output assembly contains all .dll references as EmbeddedResource.

回答1:

MSBuild. Create EmbeddedResource before build

You can try to use BeforeBuild action to the csproj file to include the embedded resources:

  <Target Name="BeforeBuild">
    ... 
    <ItemGroup>
      <EmbeddedResource Include="..."/>
    </ItemGroup>
    ...
  </Target>

Now MSBuild will add this file as embedded resource into your assembly.

Update:

Thanks @Martin Ullrich. He pointed out the correct direction, we could use <Target Name="EmbedLocal" BeforeTargets="PrepareForBuild"> in the Directory.Build.props to resolve this issue. You can check if it works for you.

  <Target Name="EmbedLocal" BeforeTargets="PrepareForBuild">
    ... 
    <ItemGroup>
      <EmbeddedResource Include="..."/>
    </ItemGroup>
    ...
  </Target>