Appdomain dynamic loading and Data Interaction

Source: Internet
Author: User
Document directory
  • Appdomain
  • Brief Introduction

In the previous project, I had the opportunity to learn the basic concepts of appdomian. Write down your learning experience. The sample can be downloaded here.

Appdomain

Appdomain is also called an application domain. It is created by CLR to regulate the scope of code execution and provide an independent error isolation mechanism. Therefore, each application package can contain one or more AppDomains, and each appdomain can be detached and managed independently.

Because appdomain is independent and does not affect each other, and the overhead of creating an appdomain and cross-appdomain is much lower than that of the process, it is often used to provide services through independent appdomain, avoid program crash due to some program errors.

Brief Introduction

By calling the sayhi object in different AppDomains, The sayhi method can be used in both Chinese and English, as well as exceptions.

  1. Multiappdomain project: The project where the default program domain is located. Used to create a secondary appdomain and call the services in the secondary appdomain to implement the sayhi call.
  2. Interface project. There is only one interface to regulate the method of calling sayhi.
  3. Sayhichinese: implement Chinese sayhi
  4. Sayhienglish: sayhi
  5. Sayhiboth: calls the sub-appdomain to implement sayhi in both Chinese and English.
  6. Sayhiexception: throws an exception during entry usage and checks the status of the secondary appdomain.

Basic appdomain Method

The default appdomain is the application domain where the application starts to run. The secondary appdomain refers to the program domain created in the default program domain or other program domains.

  • Create an appdomain.

You can create a new appdomain in the application domain or the sub-appdoman, which is managed by the current application domain. For example:

Appdomain chineseappdomain = appdomain. createdomain ("Chinese ");

Enter the name of the parameter flavor appdomain, which can be repeated. That is, you can have multiple program domains called Chinese.
By default, the directory pointed to by chineseappdomain. basedirectory is the directory of the default program domain. When the program runs, metadata is required. After the meeting, you can start searching from this directory.

  • Uninstall a program domain.

 

Appdomain. Unload (aappdomaininstance );

 
The default program domain cannot be uninstalled. Otherwise, a cannotunloadappdomainexception error is returned.
If the sub-program domain uninstalls itself, which one throws an internal system. Threading. threadabortexception exception, but system. appdomainunloadedexception can be captured externally.

  • Obtain the current appdomain
Appdomain dom = appdomain. currentdomain.

If it is in the default program domain, you can obtain the default program domain object. If it is in another sub-appdomain, you can obtain the respective appdomain.

Create the first example. In the multiappdomain project, open the file program. CS and find

Appdomain chineseappdomain = appdomain. createdomain ("Chinese ");
Appdomain englishappdomain = appdomain. createdomain ("English ");
Appdomain bothappdomain = appdomain. createdomain ("both ");
Appdomain exceptiondomain = appdomain. createdomain ("exception ");
  • Value Transfer Between AppDomains

Only instances that inherit the system. externalbyrefobject or the class that declares the serializableattribute attribute can be passed between appdomain. That is:

[Serializable]
Public Class
{}
 
Public Class B: system. externalbyrefobject
{}

Assume that instance A and instance B of instance A must be transferred from appdomain X to appdomain y. Which instance a is equivalent to object copy. Any operation on a in appdomain y will not affect a in appdomainx. B is delivered through a cross-domain transparent proxy, which is equivalent to a value reference. Therefore, in appdomain y, any operation on B affects B in appdomain X. Refer:

In appdoain, you can use the appdomain. setdata and getdata methods for access operations.

Dynamic appdomain Import

To implement the Import Control on the secondary appdomain in the default appdomain, you must obtain the example of remotloader in the secondary appdomain.

 

Before importing the file, open the remoteloader. CS file in the multiappdomain project and check the load method.

Public class remoteloader: externalbyrefobject
{
Private dictionary <string, assembly> assemblies = new dictionary <string, assembly> ();
Public void load (string fullpath)
{
Byte [] fscontent;
Using (filestream FS = file. openread (fullpath ))
{
Fscontent = new byte [fs. Length];
FS. Read (fscontent, 0, fscontent. Length );
}
Assembly = assembly. Load (fscontent );
Assemblies. Add (assembly. getname (). Name, Assembly );
}
}

In the load method, use byte to import the Assembly. This prevents the Assembly file from being exclusive. If you use the file path method to import assembly. Load (filepath), the file cannot be changed while the program is running.

Here is an aside. At the beginning of writing this example, I used the path import method, which was always smooth. When sayhi is implemented in bothsayhi, a conversion Exception error is thrown, indicating that the referenced transparent proxy (_ transparentproxy) object cannot be converted to the Isay interface type. But it is normal to paste the code in the main method. I tried n methods later, including modifying them to abstract classes and classes. I was wondering why it would be okay to accidentally change the load import to byte import.

In my opinion, it is because the main method excludes interface. dll under the DEBUG directory. The other sub-appdomain directly obtains the DLL under the interface project. Therefore, the call in the main method is successful, because the file to which the metadata belongs is only occupied by itself. However, the interface. dll in bothsayhi is used with other AppDomains. Therefore, in bothsayhi, the interface metadata needs to be obtained during conversion, while the interface is occupied by other AppDomains and cannot be read. Therefore, if metadata cannot be obtained, a conversion exception is thrown. This is just my personal idea, and I hope that there will be problems with high fingers.

Now let's get to the point where remoteloader needs to be created in the secondary appdomain and referenced in the default appdomain.
In the project multiappdomain file program. CS, find in the main function:

Remoteloader chineseloader =
(Remoteloader) chineseappdomain. createinstanceandunwrap ("multiappdomain", "multiappdomain. remoteloader ");

You can also write it as follows:

Remoteloader chineseloader =
(Remoteloader) chineseappdomain. createinstance ("multiappdomain", "multiappdomain. remoteloader"). Unwrap;

If the second method is used to create the object, the system. runtime. remoting. objecthandle object is returned. This object is defined in msdn: encapsulate value-based messages to send object references so that they can be returned through indirect addressing. Therefore, you do not need the related metadata of the default appdomain (so you do not need to import the relevant Assembly) until you use the unwarrp. Default appdomain to import the relevant metadata.
After unwrap, the object is a transparent proxy and then forced conversion. After obtaining the remoteloader proxy, import the relevant Assembly for each sub-domain, as follows:

Internal class Program
{
String chinesedll = @ ".../../sayhichinese/bin/debug/sayhichinese. dll ";
String interfacedll = @ ".../interface/bin/debug/interface. dll ";
// Omitting the code
Private Static void main (string [] ARGs)
{
// Omitting the code
Chineseloader. Load (interfacedll );
Chineseloader. Load (chinesedll );
Chineseloader. createservice ("sayhi", "sayhichinese", "sayhichinese. sayhi ");
// Omitting the code
}
}

Pay attention to chineseloader. Load (interfacedll). This sentence can be omitted (for unknown reasons at first, I was so excited for a while that I thought. Net had such a high level ). First, the file already exists in the default directory of multiappdomain (because the project displays the interface project referenced). Then, when creating the chineseappdomain, I did not specify the basedirectory of the sub-appdomain, therefore, basedirecotry points to the running directory of multiappdomain by default. In this multiappdomain project, we reference the interface, so the PATH also contains the interface. DLL, so when we call chineseloader. createservice () creates sayhichinese. when a sayhi instance is running, CLR automatically imports interfaces from the multiappdomain directory. DLL.

Because bothsayhi can be completed only after the support of the other two instances, you need to enter the instances of Chinese and English to create the code.

Bothloader. Load (interfacedll );
Bothloader. Load (bothdll); bothloader. setservicefrom ("Chinese", chineseloader. getservice ("sayhi "));
Bothloader. setservicefrom ("English", englishloader. getservice ("sayhi "));
Bothloader. createservice ("sayhi", "bothsayhi", "bothsayhi. sayhi ");

In bothsayhi, you can call Chinese and English services:
Bothsayhi Method

Public String say ()
{
Isayhi Chinese = (isayhi) appdomain. currentdomain. getdata ("Chinese ");
Isayhi English = (isayhi) appdomain. currentdomain. getdata ("English ");
Console. writeline (Chinese. Say () + "" + English. Say ());
Return Chinese. Say () + "" + English. Say ();
}

 

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.