How to use an assembly from the GAC?

2.4k views Asked by At

I have a dll in C:\Windows\Microsoft.NET\assembly\GAC_32\MyFolder\ that I want to use in my C# project.
I tried to add reference(References->Add Reference->Browse) to it and it seems fine but during runtime the program crushed with an AccessViolationException.
I wasn't sure if the reference was the problem so I decided to look into it and I found an answer in this post saying that you can't reference an assembly from the GAC this way. What I didn't find is how should I do it.
When I remove the reference to the dll the program isn't compiling of course.

2

There are 2 answers

0
Ondrej Janacek On

There are some things that you need to understand before working with GAC assemblies.

1) Assembly in GAC has to be strong-named.

2) You can't just copy the file there, here's how to deploy an assembly to GAC properly.

3) A strong-named assembly can only use types from other strong-named assemblies.

4) Here's how to reference a strong name assembly during compile-time (using a compiler option) and run-time and here's how to reference a GAC assembly from Visual Studio. Read also the answer from Hans Passant in this thread.

0
andrei.ciprian On

Possible duplicate of 'Referencing DLL from GAC in Visual Studio'. Check out especially this answer that explains why adding a reference from GAC is bad practice. However you can still do that using the full path on your machine. Consider the following scenario:

  1. your reference is a third party dll
  2. You rely on the fact that machines you are deploying to already have that dll registered

Resolution:

  1. Copy 3rd party assemblies you depend on to some folder of choice.
  2. Use those references just for compilation purposes. You are not shipping those items.
  3. Upon installation those references will be resolved from the GAC on that machine. If not, you need to install those assemblies to GAC.

This scenario is used by those who build custom apps for SharePoint (for instance).