簡體   English   中英

"如何在 nuget 中使用外部別名"

[英]How to use extern alias with nuget

我在我的項目中使用extern alias<\/code> ,所以我需要將參考別名從global<\/code>更改為其他名稱。 問題是,如果我使用 Nuget 添加引用,則每次更新包時,別名都會恢復為global<\/code> 。 有沒有辦法阻止這種情況發生?

"

這是nuget引用的已知問題; 在匯編別名的情況下根本不支持別名: https//github.com/NuGet/Home/issues/4989

幸運的是,解決方法存在; 你可以在你的csproj中添加特殊目標,它將動態分配別名:

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

感謝csproj Target更改程序集引用的別名。

我用它來修復System.Data.Services.Client / Microsoft.Data.Services.Client碰撞,就像這樣:

錯誤CS0433:類型'DataServiceContext'存在於'Microsoft.Data.Services.Client,Version = 5.8.3.0,Culture = neutral,PublicKeyToken = 31bf3856ad364e35'和'System.Data.Services.Client,Version = 4.0.0.0, Culture = neutral,PublicKeyToken = b77a5c561934e089'

解決方案是:

  <!--
  Avoid collision of older System.Data.Services.Client with newer Microsoft.Data.Services.Client
  when mixed due to PackageReferences
  -->
  <Target Name="ChangeAliasesOfNugetRefs" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
    <ItemGroup>
      <ReferencePath Condition="'%(FileName)' == 'System.Data.Services.Client'">
        <Aliases>legacy</Aliases>
      </ReferencePath>
    </ItemGroup>
  </Target>

這是不可能的,因為在nuget更新后它刪除了以前的程序集並添加了一個新的程序集,因此它刪除了程序集的別名...所以你必須再次將你的別名添加到新的更新的程序集中。

您可以向NuGet包添加安裝腳本以添加別名。 但是該軟件包的消費者將無法選擇不添加別名。 這是您可以在腳本中使用的一些代碼。 我不是PowerShell中最偉大的,所以可能有更好的方法:)

# 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM