Understanding and Using Assemblies and Namespaces in .NET

原文出处: http://msdn.microsoft.com/vstudio/using/migrate/default.aspx?pull=/library/en-us/dndotnet/html/assenamesp.asp#assenamesp_topic3

Understanding and Using Assemblies and Namespaces in .NET

Upgrading to Microsoft .NET

Mike Gunderloy

February 2002

Summary: Creating assemblies and namespaces in Microsoft Visual Basic .NET. (12 printed pages)

Objectives

  • Understand assemblies in Microsoft® .NET.
  • Understand namespaces in .NET.
  • Use Microsoft Visual Basic® .NET to create and customize an assembly.
  • Use Visual Basic .NET to create a namespace.

Assumptions

The following should be true for you to get the most out of this document:

  • You are familiar with Visual Basic programming.
  • You understand the basic concept of object-oriented programming.
  • You have access to Visual Basic .NET.

Contents

Introduction
Assemblies
Namespaces
Practice Creating an Assembly
Practice Creating a Namespace
What's New Since Visual Basic 6.0?
Summary

Introduction

Microsoft .NET provides several ways to think of your code as more than just a bunch of disconnected lines. As a Visual Basic programmer, you're already familiar with the concept of a class , a section of code that defines an object and its behavior. But two of the higher-level groupings may be unfamiliar to you:

  • An assembly provides a fundamental unit of physical code grouping.
  • A namespace provides a fundamental unit of logical code grouping.

As you'll see in this document, you can use Visual Basic .NET to create both assemblies and namespaces. You'll need to understand both of these concepts to be a productive Visual Basic .NET developer.

Assemblies

An assembly is a collection of types and resources that forms a logical unit of functionality. All types in the .NET Framework must exist in assemblies; the common language runtime does not support types outside of assemblies. Each time you create a Microsoft Windows® Application, Windows Service, Class Library, or other application with Visual Basic .NET, you're building a single assembly. Each assembly is stored as an .exe or .dll file.

> **Note **** ** Although it's technically possible to create assemblies that span multiple files, you're not likely to use this technology in most situations.

The .NET Framework uses assemblies as the fundamental unit for several purposes:

  • Security
  • Type Identity
  • Reference Scope
  • Versioning
  • Deployment

Security

An assembly is the unit at which security permissions are requested and granted. Assemblies are also the level at which you establish identity and trust. The .NET Framework provides two mechanisms for this level of assembly security: strong names and Signcode.exe. You can also manage security by specifying the level of trust for code from a particular site or zone.

Signing an assembly with a strong name adds public key encryption to the assembly. This ensures name uniqueness and prevents substituting another assembly with the same name for the assembly that you provided.

The signcode.exe tool embeds a digital certificate in the assembly. This allows users of the assembly to verify the identity of the assembly's developer by using a public or private trust hierarchy.

You can choose to use either strong names, Signcode.exe, or both, to strengthen the identity of your assembly.

The common language runtime also uses internal hashing information, in conjunction with strong names and signcode, to verify that the assembly being loaded has not been altered after it was built.

Type Identity

The identity of a type depends on the assembly where that type is defined. That is, if you define a type named DataStore in one assembly, and a type named DataStore in another assembly, the .NET Framework can tell them apart because they are in two different assemblies. Of course you can't define two different types with the same name in the same assembly.

Reference Scope

The assembly is also the location of reference information in general. Each assembly contains information on references in two directions:

  • The assembly contains metadata that specifies the types and resources within the assembly that are exposed to code outside of the assembly. For example, a particular assembly could expose a public type named Customer with a public property named AccountBalance.
  • The assembly contains metadata specifying the other assemblies on which it depends. For example, a particular assembly might specify that it depends on the System.Windows.Forms.dll assembly.

Versioning

Each assembly has a 128-bit version number that is presented as a set of four decimal pieces: Major.Minor.Build.Revision

For example, an assembly might have the version number 3.5.0.126.

By default, an assembly will only use types from the exact same assembly (name and version number) that it was built and tested with. That is, if you have an assembly that uses a type from version 1.0.0.2 of another assembly, it will (by default) not use the same type from version 1.0.0.4 of the other assembly. This use of both name and version to identify referenced assemblies helps avoid the "DLL Hell" problem of upgrades to one application breaking other applications.

> Tip An administrator or developer can use configuration files to relax this strict version checking. Look for information on publisher policy in the .NET Framework Developer's Guide.

Deployment

Assemblies are the natural unit of deployment. The Windows Installer Service 2.0 can install individual assemblies as part of a larger setup program. You can also deploy assemblies in other ways, including by a simple xcopy to the target system or via code download from a web site. When you start an application, it loads other assemblies as a unit as types and resources from those assemblies are needed.

The Assembly Manifest

Every assembly contains an assembly manifest, a set of metadata with information about the assembly. The assembly manifest contains these items:

  • The assembly name and version
  • The culture or language the assembly supports (not required in all assemblies)
  • The public key for any strong name assigned to the assembly (not required in all assemblies)
  • A list of files in the assembly with hash information
  • Information on exported types
  • Information on referenced assemblies

In addition, you can add other information to the manifest by using assembly attributes. Assembly attributes are declared inside of a file in an assembly, and are text strings that describe the assembly. For example, you can set a friendly name for an assembly with the AssemblyTitle attribute:

  1<assembly: assemblytitle("test="" project")="">
  2    
  3
  4**Table 1. Standard assembly attributes**
  5
  6**Attribute** |  **Meaning**  
  7---|---  
  8AssemblyCompany  |  Company shipping the assembly   
  9AssemblyCopyright  |  Copyright information   
 10AssemblyCulture  |  Enumeration indicating the target culture for the assembly   
 11AssemblyDelaySign  |  True to indicate that delayed signing is being used   
 12AssemblyDescription  |  Short description of the assembly   
 13AssemblyFileVersion  |  String specifying the Win32 file version. Defaults to the AssemblyVersion value.   
 14AssemblyInformationalVersion  |  Human-readable version; not used by the common language runtime   
 15AssemblyKeyFile  |  Name of the file containing keys for signing the assembly   
 16AssemblyKeyName  |  Key container containing a key pair to use for signing   
 17AssemblyProduct  |  Product Name   
 18AssemblyTitle  |  Friendly name for the assembly   
 19AssemblyTrademark  |  Trademark information   
 20AssemblyVersion  |  Version number expressed as a string.   
 21  
 22You can also define your own custom attributes by inheriting from the System.Attribute class. These attributes will be available in the assembly manifest just like the attributes listed above. 
 23
 24###  The Global Assembly Cache 
 25
 26Assemblies can be either private or shared. By default, assemblies are private, and types contained within those assemblies are only available to applications in the same directory as the assembly. But every computer with the .NET Framework installed also has a global assembly cache (GAC) containing assemblies that are designed to be shared by multiple applications. There are three ways to add an assembly to the GAC: 
 27
 28  * Install them with the Windows Installer 2.0 
 29  * Use the Gacutil.exe tool 
 30  * Drag and drop the assemblies to the cache with Windows Explorer 
 31
 32
 33
 34Note that in most cases you should plan to install assemblies to the GAC on end-user computers by using the Windows Installer. The gacutil.exe tool and the drag and drop method exist for use during the development cycle. You can view the contents of your global assembly cache by using Windows Explorer to navigate to the WINNT\assembly folder, as shown in Figure 1. 
 35
 36![](http://msdn.microsoft.com/library/en-us/dndotnet/html/assenamesp01.gif)
 37
 38**Figure 1. Viewing the Global Assembly Cache in Windows Explorer**
 39
 40###  Assembly Info.vb 
 41
 42When you create a new project using Visual Basic .NET, one of the components of the project will be a file named AssemblyInfo.vb. This file contains all of the assembly attributes that describe the assembly. To characterize your assembly, you should customize this information. You can edit the AssemblyInfo.vb file just like any other Visual Basic .NET source file. The default contents of this file look like this: 
 43    
 44    
 45    Imports System.Reflection
 46    Imports System.Runtime.InteropServices
 47    
 48    ' General Information about an assembly is controlled through 
 49        the following 
 50    ' set of attributes. Change these attribute values to modify 
 51        the information
 52    ' associated with an assembly.
 53    
 54    ' Review the values of the assembly attributes
 55    
 56    <assembly: assemblytitle("")="">
 57<assembly: assemblydescription("")="">
 58<assembly: assemblycompany("")="">
 59<assembly: assemblyproduct("")="">
 60<assembly: assemblycopyright("")="">
 61<assembly: assemblytrademark("")="">
 62<assembly: clscompliant(true)=""> 
 63    
 64    'The following GUID is for the ID of the typelib if this project 
 65       is exposed to COM
 66    <assembly: guid("0c23e636-a54a-4f44-9432-e4ed4bd3017d")=""> 
 67    
 68    ' Version information for an assembly consists of the following 
 69        four values:
 70    '
 71    '      Major Version
 72    '      Minor Version 
 73    '      Build Number
 74    '      Revision
 75    '
 76    ' You can specify all the values or you can default the Build 
 77        and Revision Numbers 
 78    ' by using the '*' as shown below:
 79    
 80    <assembly: assemblyversion("1.0.*")="">
 81    
 82
 83##  Namespaces 
 84
 85Another way to organize your Visual Basic .NET code is through the use of namespaces. Namespaces are not a replacement for assemblies, but a second organizational method that complements assemblies. Namespaces are a way of grouping type names and reducing the chance of name collisions. A namespace can contain both other namespaces and types. The full name of a type includes the combination of namespaces that contain that type. 
 86
 87###  The Namespace Hierarchy and Fully-Qualified Names 
 88
 89You're probably already familiar with namespaces from the .NET Framework Class Library. For example, the Button type is contained in the System.Windows.Forms namespace. That's actually shorthand for the situation shown in Figure 2, shows that the Button class is contained in the Forms namespace that is contained in the Windows namespace that is contained in the root System namespace. 
 90
 91![](http://msdn.microsoft.com/library/en-us/dndotnet/html/assenamesp02.gif)
 92
 93**Figure 2. A namespace and class hierarchy**
 94
 95The fully qualified name of a class is constructed by concatenating the names of all the namespaces that contain the type. For example, the fully qualified name of the Button class is System.Windows.Forms.Button. The namespace hierarchy helps distinguish types with the same name from one another. For example, you might define your own class named Button, but it might be contained in the ControlPanel Namespace within the PowerPlant namespace, making its fully qualified name PowerPlant.ControlPanel.Button. 
 96
 97&gt; **Tip** There's no need to use fully qualified names in your code unless you need to resolve an ambiguity between two types with the same type name used in the same project. 
 98
 99###  Declaring Namespaces 
100
101You can use the Namespace statement to declare a namespace in your own code. Namespace statements can be nested. For example, a Visual Basic .NET module could contain these lines of code: 
102    
103    
104    Namespace PowerPlant
105        Namespace ControlPanel
106            Public Class Button
107                ' Statements to implement Button
108            End Class
109        End Namespace
110    End Namespace
111    
112
113An alternative way to express this same hierarchy is to combine the Namespace statements: 
114    
115    
116    Namespace PowerPlant.ControlPanel
117        Public Class Button
118            ' Statements to implement Button
119        End Class
120    End Namespace
121    
122
123By default, a Visual Basic .NET project declares a _root namespace_ that has the same name as the project. If the above declaration was in a project called PowerLib, then the fully qualified name of the Button class would be PowerLib.PowerPlant.ControlPanel.Button. You can change the name of the root namespace by following these steps: 
124
125  1. In Project Explorer, right-click the project and select **Properties** . 
126  2. Click **Common Properties** . 
127  3. Enter a new name for the Root Namespace. It's good practice to use a name such as **CompanyName.Technology** for the Root Namespace, to avoid conflicts with namespaces defined by other developers. 
128  4. Click **OK** . 
129
130&gt; **Note** Strictly speaking, assemblies and namespaces are orthogonal. That is, you can declare members of a single namespace across multiple assemblies, or declare multiple namespaces in a single assembly. Unless you have a good reason for such an arrangement, though, it's best to keep things simple with one namespace per assembly and vice versa. 
131
132
133
134
135##  Practice Creating an Assembly 
136
137In the following example, you'll create a class library containing a class that exposes a single method and a single event. Then you'll use assembly attributes to customize the assembly information. 
138
139###  Create the Class Library 
140
141Follow these steps to create the class library that will raise the events: 
142
143  1. Open Microsoft Visual Studio® .NET, click **Start** , and then click **New Project** . 
144  2. In the left pane tree view, select **Visual Basic Project** . 
145  3. Select Class Library as the project template. 
146  4. Set the name of the application to **PowerLib** and click **OK** . 
147  5. In Solution Explorer, highlight the class called Class1.vb and rename it to **Button.vb** . 
148  6. Select the code for Class1 in Button.vb (this be an empty class definition) and replace it with the following code: 
149    
150        Public Class Button
151    
152        Private mfState As Boolean
153    
154        Public Sub Toggle()
155            mfState = Not mfState
156        End Sub
157    
158        Public Property State() As Boolean
159            Get
160                State = mfState
161            End Get
162            Set(ByVal Value As Boolean)
163                mfState = Value
164            End Set
165        End Property
166    
167    End Class 
168    
169
170
171
172
173###  Customize the Assembly 
174
175Follow these steps to customize the Assembly attributes: 
176
177  1. In Solution Explorer, double-click the AssemblyInfo.vb file to open it in the code editor. 
178  2. Select the first block of assembly attributes and modify them as follows: 
179    
180        <assembly: assemblytitle("powerplant")="">
181<assembly: assemblydescription("power="" interface")="" plant="" user="">
182<assembly: assemblycompany("your="" company")="">
183<assembly: assemblyproduct("powerlib")="">
184<assembly: 2002")="" assemblycopyright("copyright="">
185<assembly: assemblytrademark("")="">
186<assembly: clscompliant(true)="">
187    
188
189  3. Select the version attribute and modify it as follows: 
190    
191        <assembly: assemblyversion("1.0.0.0")="">
192    
193
194
195
196
197##  Practice Creating a Namespace 
198
199In the following example, you'll add namespace information to the PowerLib project. Follow these steps to create the namespace information: 
200
201  1. In the code editor, open the Button.vb file and add this line to the top of the module, above the declaration for the Button class: 
202    
203        Namespace ControlPanel
204    
205
206  2. Visual Basic .NET automatically creates a corresponding End Namespace statement. Move this statement below the **End Class** statement that terminates the Button class. 
207  3. In Solution Explorer, right-click the **PowerLib** project node and choose **Properties** . 
208  4. Change the Root namespace property to **PowerPlant** . 
209  5. On the **File** menu, click **Save All** . 
210
211
212
213###  Try It Out 
214
215On the **Build** menu, click **Build Solution** (or press **Ctrl+Shift+B** ) to build the project. This will create the assembly and the namespaces that it contains. To view the assembly manifest, you can use the Ildasm.exe utility that ships with the .NET Framework. Follow these steps: 
216
217  1. Click **Start** , click **Programs** , click **Microsoft Visual Studio .NET 7.0** , click **Visual Studio .NET Tools** , and then click **Visual Studio .NET Command Prompt** . 
218  2. At the command prompt, type **ildasm** and press **Enter** . 
219  3. In the ildasm interface, on the **File** menu, click **Open** . Navigate to My Documents\Visual Studio Projects\PowerLib\bin\PowerLib.dll and click **Open** . 
220  4. In the ildasm window, expand the PowerPlant.ControlPanel namespace and you'll find the Button class. Expand the class and you'll see the members of its interface. 
221  5. In the tree view, double-click the Manifest node and Ildasm will open the Manifest viewer. Scroll down and to the right and you'll find the values of your custom assembly attributes, as shown in Figure 3. 
222
223
224
225![](http://msdn.microsoft.com/library/en-us/dndotnet/html/assenamesp03.gif)
226
227**Figure 3. Viewing assembly manifest information**
228
229##  What's New Since Visual Basic 6.0? 
230
231The concepts of assemblies and namespaces are completely new to Visual Studio .NET. Visual Basic 6.0 can create class libraries, but those class libraries lack the versioning, deployment, security, and other special features of assemblies. Visual Basic 6.0 also provides no way to create a hierarchy of namespaces. 
232
233##  Summary 
234
235Visual Basic .NET allows you to group your code into logical units in several ways. First, by grouping code in assemblies, you can establish security, version, reference, and deployment boundaries. Second, by grouping classes into namespaces, you can create a hierarchy in which it's easy to identify classes by their fully qualified names. These two methods of organization complement one another, and you'll need to use both of them in your own Visual Basic .NET development. 
236
237###  About the Author 
238
239Mike Gunderloy writes about software and raises chickens in eastern Washington state. He's the co-author of _Access 2002 Developer's Handbook_ and author of _SQL Server Developer's Guide to OLAP with Analysis Services_ , both from Sybex. He's been writing code for Microsoft products since the prehistoric pre-Windows era, and has no intention of stopping any time soon. 
240
241####  About Informant Communications Group 
242
243Informant Communications Group, Inc. (www.informant.com) is a diversified media company focused on the information technology sector. Specializing in software development publications, conferences, catalog publishing and Web sites, ICG was founded in 1990. With offices in the United States and the United Kingdom, ICG has served as a respected media and marketing content integrator, satisfying the burgeoning appetite of IT professionals for quality technical information. 
244
245Copyright © 2002 Informant Communications Group and Microsoft Corporation 
246
247Technical editing: KNG Consulting 
248
249![Top of Page](http://msdn.microsoft.com/msdn-online/shared/graphics/top.gif) Top of Page</assembly:></assembly:></assembly:></assembly:></assembly:></assembly:></assembly:></assembly:></assembly:></assembly:></assembly:></assembly:></assembly:></assembly:></assembly:></assembly:></assembly:></assembly:>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus