Jul 4, 2014

Strong naming an assembly

In .NET assemblies can be broadly classified into 2 types
  1. Weak Named Assemblies 2. Strong Named Assemblies

Strong naming an assembly or Signing an assembly with strong name.

An assembly name consists of 4 Parts
 
1. Simple textual name.
2. Version number.
3. Culture information (If provided, otherwise the assembly is language neutral)
4. Public key token 


We use AssemblyVersion attribute to specify the Assembly version. 


The default is 1.0.0.0. The version number of an assembly consists of the following four parts:
1. Major Version
2. Minor Version
3. Build Number
4. Revision Number 


You can specify all the values or you can default the Revision and Build Numbers by using the '*' as shown below:
[assembly: AssemblyVersion("2.1.*")]  



AssemblyCulture attribute is used for specifying the culture. By default an assembly is language neutral, as the AssemblyCulture attribute contains empty string. If you specify any string other than an empty string for the culture parameter, the assembly becomes a satellite assembly. In fact, compilers use this attribute to distinguish between main assembly (language neutral) and a satellite assembly.  

We use AssemblyKeyFile attribute to sign the assembly with a strong name. To the constructor of AssemblyKeyFile attribute, we need to pass the path of the key file, that contains the private and public key. To generate the key file
1. Open Visual Studio Command Prompt
2. Type the command and press enter: sn.exe -k c:\KeyFile.snk


The key file with name KeyFile.snk should be generated in the C: drive. In SN.exe, SN stands for Strong Name. Key files have the extension of .snk


Finally, In AssemblyInfo.cs file of the project, specify AssemblyKeyFile attribute as shown below and build the project. This process will strongly name an assembly.
[assembly: AssemblyKeyFile("KeyFile.snk")]


A strongly named assembly should have all of the following

 
1. The textual assembly name.
2. The assembly Version number.
3. The assembly should have been signed with private/public key pair.


If the assembly is not signed with private/public key pair, the assembly is weak named and not guaranteed to be unique, and may cause DLL hell. Strong named assemblies are guaranteed to be unique and solves DLL hell. You cannot install an assembly into GAC unless, the assembly is strongly named.  

No comments:

Post a Comment