Search code examples
c#msbuildnuget

How to use Project's Assembly information when building NuGet package using MSBuild?


How can I use the assembly information from the project to pass and use by NuGet package when creating NuGet package using MSBuild.

Assembly Information

</Project>
<PropertyGroup>
   <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
    <PackageId>Test</PackageId>
    <PackageVersion Condition=""></PackageVersion>
    <Title>Testing</Title>
    <Authors>Hugh</Authors>
    <PackageIcon>Hugh.png</PackageIcon>
    <PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
    <Description>test</Description>
    <PackageTags>test</PackageTags>
    <PackageReleaseNotes>Update.</PackageReleaseNotes>
    <copyright>Copyright © 2021 </copyright>
  </PropertyGroup>
  <ItemGroup>
    <None Include="Resources\test.png" Pack="true" PackagePath="" />
  </ItemGroup>
</Project>

I want the NuGet Package ID to set as Assembly Title, Description as Assembly Description, Author as Company, PackageVersion as Assembly Version and so on.

  <Target Name="RetrieveIdentities">
    <GetAssemblyIdentity
        AssemblyFiles="$(MyAssemblies)">
      <Output
          TaskParameter="Assemblies"
          ItemName="MyAssemblyIdentities"/>
    </GetAssemblyIdentity>

    <Message Text="Files: %(MyAssemblyIdentities.Version)"/>
  </Target>

I have tried using the above target but couldn't succeed and not sure to use or reference %(MyAssemblyIdentities.Version) in Package Version under PropertyGroup for NuGet package.

Please advise ?


Solution

  • Reusing MSBuild variables is enough for syncing AssemblyTitle with PackageId (as far as naming restrictions allow) and Company with Authors etc.. No targets required.

    <Project Sdk="Microsoft.NET.Sdk">
        <PropertyGroup>
            <TargetFramework>net6.0</TargetFramework>
            <ImplicitUsings>enable</ImplicitUsings>
            <Nullable>enable</Nullable>
        </PropertyGroup>
    
        <PropertyGroup>
            <AssemblyTitle>Some Title</AssemblyTitle>
            <Company>Some Company</Company>
            <Description>Some Description</Description>
    
            <PackageId>$(AssemblyTitle.Replace(" ", "_"))</PackageId>
            <Authors>$(Company)</Authors>
    
            <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
        </PropertyGroup>
    </Project>
    

    When building this with

    dotnet build -p:Version=1.2.3
    

    (or adding the Version property to the csproj), the build will by default use the given Version as both package version and assembly version.

    The package then looks like this, which should address every requirement from your question: enter image description here