Thursday, January 10, 2008

How to install assembly to GAC?

In order to share a .NET assembly with multiple applications installed on the same machine, it needs to be installed into the Global Assembly Cache (GAC). This article will walk you through the process of giving your assembly a strong name, and installing it into the GAC.
The Contrived .NET class

using System;

public class aspZone
{
public int Add(int x, int y)
{
return(x + y);
}
}


Listing 1 - dotNETComponent.cs

The code in Listing 1 is the same contrived sample you've seen in other articles on this site. But to be installed in the GAC, it needs to be given a Strong Name.
What's in a Strong Name?

A strong name is made up of the full class name including the namespace, the version number, culture information (which can be null if culture neutral), plus a public key and a digital signature.

The .NET Framework provides a utility to create a key pair (sn.exe). Run the following at a command line.


C:\dotNET>sn -k dotNETComponent.snk

Microsoft ® .NET Framework Strong Name Utility
Version 1.0.2914.16
Copyright © Microsoft Corp. 1998-2001. All rights reserved.

Key pair written to dotNETComponent.snk

C:\dotNET>


Output 1 - sn.exe
Then add the necessary attributes to the .cs file as shown in Listing 2.


using System;
using System.Reflection;

[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyKeyFile("dotNETComponent.snk")]
public class aspZone
{
public int Add(int x, int y)
{
return(x + y);
}
}


Listing 2 - dotNETComponent.cs
Then compile the assembly.

C:\dotNET>csc -t:library dotNETComponent.cs


Microsoft ® Visual C# Compiler
Version 7.00.9254 [CLR version v1.0.2914]
Copyright © Microsoft Corp 2000-2001. All rights reserved.

Output 2 - csc.exe

Installing the assembly into the GAC

From a command prompt, in the same directory where dotNETComponent.dll resides, run gacutil.exe as seen in Output 3 below:

C:\dotNET>gacutil /i dotNETComponent.dll

Microsoft ® .NET Global Assembly Cache Utility.
Version 1.0.2914.16
Copyright © Microsoft Corp. 1998-2001. All rights reserved.

Assembly successfully added to the cache

C:\dotNET>

Output 3 - gacutil.exe

The assembly can now be used from other assemblies on the server, regardless of their physical location.

No comments: