Core Concepts: Assemblies
Introduction to Assemblies
In .NET, an assembly is a compiled code library used for deployment, versioning, and security. An assembly is a building block of .NET applications; it can be a .dll or .exe file. Assemblies contain one or more managed types along with metadata about those types.
Key Features of Assemblies
- Self-describing via metadata
- Versioning and deployment unit
- Security boundary
- Encapsulation of code
Example: Creating a Simple Assembly
Here's an example of how to create a simple assembly in C#:
// File: HelloWorld.cs
using System;
namespace HelloWorld
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
Compile this file using the C# compiler:
csc /target:library /out:HelloWorld.dll HelloWorld.cs
This command generates an assembly named HelloWorld.dll
.
Components of an Assembly
An assembly consists of four key components:
- Manifest: Contains metadata about the assembly.
- Type Metadata: Information about types defined in the assembly.
- MSIL Code: Intermediate language code executed by the CLR.
- Resources: Additional files like images, strings, etc., required by the assembly.
Example: Viewing Assembly Metadata
You can use tools like ILDASM (Intermediate Language Disassembler) to view the metadata of an assembly. Here is how you can use ILDASM:
ildasm HelloWorld.dll
This command opens a window displaying the structure and metadata of the HelloWorld.dll
assembly.
Strong-Named Assemblies
A strong-named assembly has a unique identity that consists of its name, version number, culture information, and a public key token. Strong names provide a unique identity to the assembly.
Example: Creating a Strong-Named Assembly
First, generate a key pair using the sn
utility:
sn -k MyKey.snk
Next, compile the assembly with the strong name:
csc /target:library /out:HelloWorld.dll /keyfile:MyKey.snk HelloWorld.cs
This command creates a strong-named assembly HelloWorld.dll
signed with MyKey.snk
.
Global Assembly Cache (GAC)
The Global Assembly Cache (GAC) is a machine-wide code cache for storing assemblies that are intended to be shared by multiple applications on the computer. Assemblies must have a strong name to be placed in the GAC.
Example: Installing an Assembly to the GAC
Use the gacutil
tool to install an assembly to the GAC:
gacutil -i HelloWorld.dll
This command installs the HelloWorld.dll
assembly to the GAC, making it available for shared use by multiple applications.
Conclusion
Assemblies are a fundamental part of the .NET framework, serving as the building blocks for applications and libraries. They provide a way to encapsulate and manage code, ensure versioning and deployment consistency, and enforce security boundaries.