How to use an external alias with nuget

I use extern aliasin my project, so I need to change the reference alias from globalto something else. The problem is that if I use Nuget to add a link, every time I update the package, the alias returns to global. Is there any way to stop this?

+3
source share
3 answers

This is a known issue with nuget links; in case of failure, the alias is not supported at all (yet): https://github.com/NuGet/Home/issues/4989

Fortunately, a workaround exists; you can add a special target to your csproj that will assign aliases on the fly:

  <Target Name="ChangeAliasesOfNugetRefs" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
    <ItemGroup>
      <ReferencePath Condition="'%(FileName)' == 'CoreCompat.System.Drawing'">
        <Aliases>CoreCompatSystemDrawing</Aliases>
      </ReferencePath>
    </ItemGroup>
  </Target>
+3

, nuget , ... .

+1

You can add install script to your NuGet package to add an alias. But the consumer of the package could not refuse to add an alias. Here is the code you can use in the script. I'm not the best in PowerShell, so there may be a better way to do this :)

# Standard Install.ps1 parameter list
param($installPath, $toolsPath, $package, $project)

# Name of the alias
$alias = 'MyAlias'

# Load the Microsoft.Build assembly to be able to access MS Build types
Add-Type -AssemblyName Microsoft.Build

# Load the csproj file
$projectObject = New-Object Microsoft.Build.Evaluation.Project($project.FullName)

# Search through the project items to find all references
$referenceItems = $projectObject.Items | where ItemType -eq "Reference" 

# Find the reference that matches the package id 
# (this assumes your assembly name matches your package id)
$item = $referenceItems | select @{Name='Reference'; Expression={$_}},@{Name='AssemblyName'; Expression={(New-Object System.Reflection.AssemblyName($_.UnevaluatedInclude)).Name}} | where AssemblyName -eq $package.Id | select Reference

# If the reference doesnt already have an alias, add one and save the project
if (($item.Reference.Metadata | where Name -eq 'Aliases') -eq $null) {
    $item.Reference.SetMetadataValue('Aliases', $alias)
    $projectObject.Save()
}

# Unload the project when done
$projectObject.ProjectCollection.UnloadAllProjects()
+1
source

Source: https://habr.com/ru/post/1613640/


All Articles