Referencing GAC Assembly in SDK Project

With the “old” project files, i.e. non-SDK projects, you could reference an assembly and it would automatically be looked up in the GAC (Global Assembly Cache). For SDK projects this was a deliberate breaking change with the reasoning, that the GAC is supposed to be used for runtime resolution and not build-time resolution. This also prevents all the issues where a build would accidentally pick up some assemblies from the GAC and then fail to run on the target machine due to missing or mismatching assemblies.

Note: This only applies to .NET Framework projects and if you build with MSBuild directly or within Visual Studio, if you use dotnet build then the following method does not work.

Sometimes you do however want to reference an assembly in the GAC from a project. In those cases there’s a configuration that allows you to opt-in to the old behavior.

<PropertyGroup>
  <AssemblySearchPaths>$(AssemblySearchPaths);{GAC}</AssemblySearchPaths>
</PropertyGroup>
<ItemGroup>
  <Reference Include="MyAssemblyInTheGAC" />
</ItemGroup>

This adds the GAC again back to the assembly search paths and as such the project will correctly resolve any references that are found in the GAC, in this example MyAssemblyInTheGAC.

What about dotnet build?

dotnet build has a different way to resolve assemblies, as such the <AssemblySearchPaths> isn’t being used and the GAC remains not found, even for a .NET Framework application.

You can use a <HintPath> to hardcode the GAC path directly, which however limits you to that one specific version and requires for it to exist on all machines that try to build your application.

<ItemGroup>
  <Reference Include="MyAssemblyInTheGAC">
    <HintPath>C:\Windows\Microsoft.NET\assembly\GAC_MSIL\MyAssemblyInTheGAC\v4.0_10.20_01be4f61be0c56c4\MyAssemblyInTheGAC.dll</HintPath>
  </Reference>
</ItemGroup>

For an additional alternative see the section below.

What About .NET?

The concept of the GAC is a .NET Framework concept and as such this isn’t relevant anymore for any of the newer .NET versions.

Maybe the actual issue is, that a third-party software that is being installed separately is providing you the DLL and as such you don’t want to ship your own and simply want to reuse that DLL. In that case, your third-party software might have fixed installation path, which allows you to use <HintPath>, see the section above, or maybe they provide an environment variable that you could reuse for the hint path.

<ItemGroup>
  <Reference Include="TheirAssembly">
    <HintPath>$(AwesomeThirdParty)/bin/TheirAssembly.dll</HintPath>
  </Reference>
</ItemGroup>

References

Leave a Comment

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.