This is a common task for developers, to add an assembly to the Global Assembly Cache (GAC). The GAC is a shared location of computer where we can put an assembly so that it will be accessible from many locations, I mean so it is accessible from another project or application. It's always a good practice to provide a strong name to a public assembly, I mean the assembly to be registered in the GAC otherwise the DLL hell problem may occur.
So, let's start by creating one class library application. Here is my sample class library project.
I have created a very simple class with one function as in the following.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClassLibrary
{
public class myClass
{
public string myFunction(string name)
{
return "Hello : " + name;
}
}
}
Now, as indicated previously, we will provide a strong name for the assembly. So right-click on the project and go to the properties.
In the properties window you will find the “Signing” tab. Here, we can sign our assembly to provide a strong name.
Just check the checkbox “Sign the assembly” and the following dropdown will become active. Select “new” from the dropdown and another popup window will open to accept filename and password.
Let's provide some file name and password for it. You are allowed to choose the signature algorithm. Just press OK to make a signature.
Then we will find one .pfx file in the solution. Now let's compile the project and go to the Debug folder of the application. You will find a DLL file.
Fine, the assembly is ready for use. Now open a command prompt in “Administrator” mode and run gacutil.exe.
There will be a separate version of the gacutil.exe in the system for each version of .NET. I am using gacutil.exe for .NET framework 4.0 and we are passing a “-i” parameter to install the assembly in the GAC. To unregister the parameter will be “-u”.
Now, once registered successfully, we will find the assembly in the following location. The file is registered in this location instead of “Window/assembly” because we have used the .NET framework's gacutil.exe to register.
If we want to use the assembly in other application, just provide reference of the assembly from same location.
And you are allowed to use it as in the following.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClassLibrary;
namespace ConsoleAPP
{
class Program
{
static void Main(string[] args)
{
myClass obj = new myClass();
Console.WriteLine(obj.myFunction("Sourav"));
Console.ReadLine();
}
}
}
And here is output.
FinallyIt's always suggested to provide a strong name of the assembly before registering it in the GAC so then multiple versions of the same assembly can exist simultaneously in the same location.