Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use extern alias with nuget

Tags:

c#

nuget

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

like image 755
Eliezer Steinbock Avatar asked Nov 01 '15 09:11

Eliezer Steinbock


People also ask

How do I use extern alias?

In order to use extern aliases, you first need to open the . csproj file of your project and modify the PackageReference or ProjectReference by adding the <Aliases> attribute. Then in any file where you want to reference either project, simply use the following directive to make a distinction between both assemblies.

How do I reference an existing NuGet package from a new project?

NET or . NET Core project. After you install a NuGet package, you can then make a reference to it in your code with the using <namespace> statement, where <namespace> is the name of package you're using. After you've made a reference, you can then call the package through its API.

What is ExcludeAssets?

ExcludeAssets. These assets will not be consumed. none. PrivateAssets. These assets will be consumed but won't flow to the parent project.


2 Answers

This is know issue with nuget references; in case of assembly alias is not supported at all (yet): https://github.com/NuGet/Home/issues/4989

Fortunately workaround exists; you can add 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>
like image 167
Vitaliy Fedorchenko Avatar answered Oct 07 '22 15:10

Vitaliy Fedorchenko


Thank You for the csproj Target to change aliases of assembly references.

I have used it to fix System.Data.Services.Client/Microsoft.Data.Services.Client collision like this one:

error CS0433: The type 'DataServiceContext' exists in both 'Microsoft.Data.Services.Client, Version=5.8.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' and 'System.Data.Services.Client, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'

The solution is:

  <!--
  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>
like image 34
Marek Ištvánek Avatar answered Oct 07 '22 14:10

Marek Ištvánek