C # Introduction to the Assembly. Load, assembly. LoadFile and assembly. loadfrom methods of reflection

Source: Internet
Author: User

Some knowledge about C # reflection is estimated to reach the maximum degree of API use. For more information, it is difficult to estimate the current level. So in the following article, as a summary of a stage.

For the reflection summary, I want to expand from the following aspects: First, reflection assembly, module, class member and member information; then, dynamic call of the class member method; the third aspect is the dynamic generation of assembly, modules, classes, and class members. Now, let's start by reflecting all kinds of information.

In C #, we need to use reflection. First, we need to understand the relationships between several classes in the following namespace:

System. Reflection namespace

(1) appdomain: application domain, which can be understood as a logical container of a group of assemblies

(2) Assembly: Assembly class

(3) module: module class

(4) type: Use reflection to obtain the core class of the type information.

An appdomain can contain N assemblies, an assembly can contain N modules, and a module can contain N types.

The appdomain class will be explained later. Let's first focus on Assembly classes

In the program, what if we want to dynamically load an assembly? There are several ways to use static methods of Assembly: load, loadfrom, and loadwithpartialname.

Let's first explain assembly. load method. This method has multiple overloaded versions. One of them is to provide detailed information about the Assembly, that is, the Assembly ID, including the Assembly name, version, region information, and public key tag, all are provided in the form of a string, such as: "myassembly, version = 1.0.0.0, culture = ZH-CN, publickeytoken = 47887f89771bc57f ".

So what is the order in which the Assembly is loaded using assembly. load? First, it will go to the Global Assembly Cache for search, then to the application root directory, and finally to the application's private path for search.

Of course, if you are using a weak named Assembly, that is, only the Assembly name is given, then CLR will not apply any security or deployment policies on the Assembly at this time, in addition, load does not go to the global cache program to find the assembly.

An example of testing to load a weak naming assembly is as follows:

(1) create a project for the console application and check "create SOLUTION ".

(2) create a new class library project in the solution, and write a class and a method at will.

(3) In the console project, add the following code directly in the main method without adding a reference:

Assembly = assembly. Load ("myassembly ");

If (assembly! = NULL)

{Console. writeline ("loaded successfully ");}

If the program is executed, an exception is thrown, indicating that the Assembly cannot be found. Why? Because we use a weak named assembly, the load method will not be searched in the Global Assembly Cache, and the Assembly is not found in the application directory, so the program cannot be found. At this time, we need to modify the program slightly without adding code. We only need to add a reference to myassembly and re-run the program. The load is successful.

Next, let's take a look at how load loads a strongly-named Assembly. This step is a little complicated. Find the directory where the myassembly. dll Assembly is located, usually in the bin "DEBUG directory

(1) generate the key pair file Sn-K myassemblykey. Keys

You can also create a key pair file name by yourself.

(2) generate a public key file

Sn-P myassemblykey. Keys myassemblypublickey. publickey

Note: view the public key command: Sn-TP myassemblypublickey. publickey

(3) create a strongly-named assembly.

It's easy to add the following features to the code that declares the namespace:

[Assembly: assemblykeyfileattribute (@ "D:" test "myassemblykey. Keys")]

(4) compile the project

(5) Add the assembly to the global cache of the Assembly

Gacutil-I myassembly. dll

At this time, go to the loaded assembly project and change the parameter in the load method to "assembly name, version = version, culture = region information, publickeytoken = Public Key", then remove the reference to the Assembly and we will find that the program runs successfully. Indicates that the Assembly is found in the global cache.

You can use the load method to load an assembly, especially a strongly-named assembly, to apply security and deployment policies on the Assembly. We recommend that you use this method to dynamically load the assembly, as for loadfrom and loadwithpartialname.

First, let's take a look at the loadfrom method. The principle of this method is as follows: if we want to use it to dynamically load the Assembly, we must tell it the Assembly path, that is, under which directory, CLR will load the Assembly that exactly matches the path you specified. Remember, when we specify the assembly path, we cannot include any information about strong names of the Assembly. Therefore, CLR will not apply any policies to the specified Assembly file, in addition, it won't go to any other place to search for the Assembly. In short, it refers to the location where the Assembly is located.

For example, if you have an assembly in D:/test/myassembly. dll and you want to use assembly. loadfrom to load the assembly, the Code is as follows:

Assembly = assembly. loadfrom (@ "D:/test/myassembly. dll ");

For the loadwithparitalname method, it is recommended that you do not use it, because the program cannot determine which assembly version is to be loaded, so here is a brief introduction of its working principle: you can pass an assembly identifier to it, including the Assembly name. Other information is optional (region information, public key, etc.). When this method is executed, checks the qualifyassembly node of the configuration file in the application. If yes, replace the Assembly with the complete assembly ID. If no, the Assembly name is first searched under the application root directory, and then the private directory. If it is not found, it is searched in the global cache of the Assembly. The simple process is as follows:

Application root directory-> application private directory-> Assembly Global cache.

The differences between the Assembly. Load () method, assembly. loadfrom () method, and assembly. LoadFile () method!

1, assembly. Load ()

This method loads an assembly by using the Assembly's long name (including the Assembly name, version information, language culture, and public key tag) and loads other Assembly referenced by the Assembly, generally, this method should be used first. Its execution efficiency is much higher than loadfrom, and it will not cause repeated loading problems (the reason is described at 2nd points)

When using this method, CLR will apply certain policies to find the Assembly. In fact, CLR locates the assembly in the following order:

(1) If the Assembly has a strong name, first find the assembly in the global assembly easing (GAC.

(2) If the strong name of the Assembly is not correctly specified or cannot be found in GAC, you can find it through the URL specified by the <codebase> element in the configuration file.

(3) If a strong name is not specified or cannot be found in GAC, CLR detects a specific folder:

Assume that your application directory is C:/appdir. In the <probing> element, privatepath specifies a path path1. The Assembly you want to locate is assemblyname. DLL, CLR locates the assembly in the following order

C:/appdir/assemblyname. dll

C:/appdir/assemblyname. dll

C:/appdir/path1/assemblyname. dll

C:/appdir/path1/assemblyname. dll

If the above method cannot find the Assembly, a compilation error will occur. If the Assembly is dynamically loaded, an exception will be thrown at runtime!

2, assembly. loadfrom ()

This method loads the Assembly from the specified path. When this method is called, the CLR will open this file to obtain information such as the assembly version, language culture, and public key tag, pass them to the load method. Then, the load method uses the above policy to find the assembly. If an assembly is found, it is compared with the path specified in the loadfrom method. If the path is the same, the Assembly is considered to be part of the application. If the path is different or the load method does not find the assembly, the Assembly is loaded as a "data file" and will not be considered as part of the application. This is why the load method mentioned at is more efficient than the loadfrom method. In addition, because the Assembly may be loaded as a "data file", when loadfrom is used to load the same assembly from different paths, it will cause repeated loading. Of course, this method will load other Assembly referenced by this Assembly.

3, assembly. LoadFile ()

This method loads the Assembly from the specified file. The difference with the above method is that this method does not load other Assembly referenced by this Assembly!

Conclusion: Generally, the load method should be preferred to load the Assembly. If you need to use the loadfrom method, you 'd better change the design and use the load method instead!

Differences between Assembly. LoadFile and assembly. loadfrom

1. assembly. loadFile only loads the corresponding DLL file, such as assembly. loadFile ("ABC. DLL "), load ABC. DLL, if ABC. def. def. the DLL is not loaded.

Assembly. loadfrom is different. It loads the DLL file and other DLL referenced by it. For example, in the above example, Def. dll is also loaded.

2. Use assembly. when loadfrom loads an assembly, it first checks whether the Assembly with the same name has been loaded before, such as ABC. the dll has two versions (version 1 is in directory 1 and Version 2 is in directory 2). Version 1 is loaded at the beginning of the program, and assembly is used. loadfrom ("2 // ABC. DLL ") when loading version 2, it cannot be loaded, but returns version 1. Assembly. LoadFile does not perform this check. For example, if the preceding example is replaced by Assembly. LoadFile, version 2 can be correctly loaded.

LoadFile: load the content of the Assembly file in the specified path. Loadfrom: loads the content of the Assembly file according to the Assembly file name.

Differences:

The LoadFile method is used to load and check the assemblies that have the same identity but are located in different paths, but do not load program dependencies.

Loadfrom cannot be used to load an assembly with the same ID but different paths.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.