其他分享
首页 > 其他分享> > Best Practices for Assembly Loading

Best Practices for Assembly Loading

作者:互联网

原文链接

 

This article discusses ways to avoid problems of type identity that can lead to InvalidCastExceptionMissingMethodException, and other errors. The article discusses the following recommendations:

The first recommendation, understand the advantages and disadvantages of load contexts, provides background information for the other recommendations, because they all depend on a knowledge of load contexts.

 

Understand the Advantages and Disadvantages of Load Contexts

Within an application domain, assemblies can be loaded into one of three contexts, or they can be loaded without context:

The execution contexts have advantages and disadvantages, as discussed in the following sections.

 

Load-From Context

The load-from context lets you load an assembly from a path that is not under the application path, and therefore is not included in probing. It enables dependencies to be located and loaded from that path, because the path information is maintained by the context.

In addition, assemblies in this context can use dependencies that are loaded into the default load context.

Loading assemblies by using the Assembly.LoadFrom method, or one of the other methods that load by path, has the following disadvantages:

No Context

Loading without context is the only option for transient assemblies that are generated with reflection emit. Loading without context is the only way to load multiple assemblies that have the same identity into one application domain. The cost of probing is avoided.

Assemblies that are loaded from byte arrays are loaded without context unless the identity of the assembly, which is established when policy is applied, matches the identity of an assembly in the global assembly cache; in that case, the assembly is loaded from the global assembly cache.

Loading assemblies without context has the following disadvantages:

Avoid Binding on Partial Assembly Names

Partial name binding occurs when you specify only part of the assembly display name (FullName) when you load an assembly. For example, you might call the Assembly.Load method with only the simple name of the assembly, omitting the version, culture, and public key token. Or you might call the Assembly.LoadWithPartialName method, which first calls the Assembly.Load method and, if that fails to locate the assembly, searches the global assembly cache and loads the latest available version of the assembly.

Partial name binding can cause many problems, including the following:

Because of the problems it can cause, the LoadWithPartialName method has been marked obsolete. We recommend that you use the Assembly.Load method instead, and specify full assembly display names. See Understand the Advantages and Disadvantages of Load Contexts and Consider Switching to the Default Load Context.

If you want to use the LoadWithPartialName method because it makes assembly loading easy, consider that having your application fail with an error message that identifies the missing assembly is likely to provide a better user experience than automatically using an unknown version of the assembly, which might cause unpredictable behavior and security holes.

 

Avoid Loading an Assembly into Multiple Contexts

Loading an assembly into multiple contexts can cause type identity problems. If the same type is loaded from the same assembly into two different contexts, it is as if two different types with the same name had been loaded. An InvalidCastException is thrown if you try to cast one type to the other, with the confusing message that type MyType cannot be cast to type MyType.

 

For example, suppose that the ICommunicate interface is declared in an assembly named Utility, which is referenced by your program and also by other assemblies that your program loads. These other assemblies contain types that implement the ICommunicate interface, allowing your program to use them.

Now consider what happens when your program is run. Assemblies that are referenced by your program are loaded into the default load context. If you load a target assembly by its identity, using the Load method, it will be in the default load context, and so will its dependencies. Both your program and the target assembly will use the same Utility assembly.

However, suppose you load the target assembly by its file path, using the LoadFilemethod. The assembly is loaded without any context, so its dependencies are not automatically loaded. You might have a handler for the AppDomain.AssemblyResolveevent to supply the dependency, and it might load the Utility assembly with no context by using the LoadFile method. Now when you create an instance of a type that is contained in the target assembly and try to assign it to a variable of type ICommunicate, an InvalidCastException is thrown because the runtime considers the ICommunicate interfaces in the two copies of the Utility assembly to be different types.

 

There are many other scenarios in which an assembly can be loaded into multiple contexts. The best approach is to avoid conflicts by relocating the target assembly in your application path and using the Load method with the full display name. The assembly is then loaded into the default load context, and both assemblies use the same Utility assembly.

If the target assembly must remain outside your application path, you can use the LoadFrom method to load it into the load-from context. If the target assembly was compiled with a reference to your application's Utility assembly, it will use the Utility assembly that your application has loaded into the default load context. Note that problems can occur if the target assembly has a dependency on a copy of the Utility assembly located outside your application path. If that assembly is loaded into the load-from context before your application loads the Utilityassembly, your application's load will fail.

The Consider Switching to the Default Load Context section discusses alternatives to using file path loads such as LoadFile and LoadFrom.

 

Avoid Loading Multiple Versions of an Assembly into the Same Context

Loading multiple versions of an assembly into one load context can cause type identity problems. If the same type is loaded from two versions of the same assembly, it is as if two different types with the same name had been loaded. An InvalidCastException is thrown if you try to cast one type to the other, with the confusing message that type MyType cannot be cast to type MyType.

For example, your program might load one version of the Utility assembly directly, and later it might load another assembly that loads a different version of the Utilityassembly. Or a coding error might cause two different code paths in your application to load different versions of an assembly.

In the default load context, this problem can occur when you use the Assembly.Loadmethod and specify complete assembly display names that include different version numbers. For assemblies that are loaded without context, the problem can be caused by using the Assembly.LoadFile method to load the same assembly from different paths. The runtime considers two assemblies that are loaded from different paths to be different assemblies, even if their identities are the same.

In addition to type identity problems, multiple versions of an assembly can cause a MissingMethodException if a type that is loaded from one version of the assembly is passed to code that expects that type from a different version. For example, the code might expect a method that was added to the later version.

More subtle errors can occur if the behavior of the type changed between versions. For example, a method might throw an unexpected exception or return an unexpected value.

Carefully review your code to ensure that only one version of an assembly is loaded. You can use the AppDomain.GetAssemblies method to determine which assemblies are loaded at any given time.

 

Consider Switching to the Default Load Context

Examine your application's assembly loading and deployment patterns. Can you eliminate assemblies that are loaded from byte arrays? Can you move assemblies into the probing path? If assemblies are located in the global assembly cache or in the application domain's probing path (that is, its ApplicationBase and PrivateBinPath), you can load the assembly by its identity.

If it is not possible to put all your assemblies in the probing path, consider alternatives such as using the .NET Framework add-in model, placing assemblies into the global assembly cache, or creating application domains.

Consider Using the .NET Framework Add-In Model

If you are using the load-from context to implement add-ins, which typically are not installed in the application base, use the .NET Framework add-in model. This model provides isolation at the application domain or process level, without requiring you to manage application domains yourself. For information about the add-in model, see Add-ins and Extensibility.

Consider Using the Global Assembly Cache

Place assemblies in the global assembly cache to get the benefit of a shared assembly path that is outside the application base, without losing the advantages of the default load context or taking on the disadvantages of the other contexts.

Consider Using Application Domains

If you determine that some of your assemblies cannot be deployed in the application's probing path, consider creating a new application domain for those assemblies. Use an AppDomainSetup to create the new application domain, and use the AppDomainSetup.ApplicationBase property to specify the path that contains the assemblies you want to load. If you have multiple directories to probe, you can set the ApplicationBase to a root directory and use the AppDomainSetup.PrivateBinPathproperty to identify the subdirectories to probe. Alternatively, you can create multiple application domains and set the ApplicationBase of each application domain to the appropriate path for its assemblies.

Note that you can use the Assembly.LoadFrom method to load these assemblies. Because they are now in the probing path, they will be loaded into the default load context instead of the load-from context. However, we recommend that you switch to the Assembly.Load method and supply full assembly display names to ensure that correct versions are always used.

 

标签:load,Loading,assembly,assemblies,application,Practices,context,loaded,Assembly
来源: https://www.cnblogs.com/panpanwelcome/p/10475985.html