如何使用nuget的extern别名

我在项目中使用extern alias ,因此我需要将引用别名从global更改为其他内容。 问题是如果我使用Nuget添加引用,每次更新包时别名都会恢复为global 。 有没有办法阻止这种情况发生?

这是nuget引用的已知问题; 如果组装别名完全不支持(还): https : //github.com/NuGet/Home/issues/4989

幸运的是,解决方法存在; 您可以在csproj中添加特殊目标,以便即时分配别名:

     CoreCompatSystemDrawing    

这是不可能的,因为在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() 

感谢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′

解决方案是:

      legacy