原文链接

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 default load context contains assemblies found by probing the global assembly cache, the host assembly store if the runtime is hosted (for example, in SQL Server), and the ApplicationBase and PrivateBinPath of the application domain. Most overloads of the Load method load assemblies into this context.

  • The load-from context contains assemblies that are loaded from locations that are not searched by the loader. For example, add-ins might be installed in a directory that is not under the application path. Assembly.LoadFromAppDomain.CreateInstanceFrom, and AppDomain.ExecuteAssembly are examples of methods that load by path.

  • The reflection-only context contains assemblies loaded with the ReflectionOnlyLoad and ReflectionOnlyLoadFrom methods. Code in this context cannot be executed, so it is not discussed here. For more information, see How to: Load Assemblies into the Reflection-Only Context.

  • If you generated a transient dynamic assembly by using reflection emit, the assembly is not in any context. In addition, most assemblies that are loaded by using the LoadFile method are loaded without context, and assemblies that are loaded from byte arrays are loaded without context unless their identity (after policy is applied) establishes that they are in the global assembly cache.

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:

  • If an assembly with the same identity is already loaded, LoadFrom returns the loaded assembly even if a different path was specified.

  • If an assembly is loaded with LoadFrom, and later an assembly in the default load context tries to load the same assembly by display name, the load attempt fails. This can occur when an assembly is deserialized.

  • If an assembly is loaded with LoadFrom, and the probing path includes an assembly with the same identity but in a different location, an InvalidCastExceptionMissingMethodException, or other unexpected behavior can occur.

  • LoadFrom demands FileIOPermissionAccess.Read and FileIOPermissionAccess.PathDiscovery, or WebPermission, on the specified path.

  • If a native image exists for the assembly, it is not used.

  • The assembly cannot be loaded as domain-neutral.

  • In the .NET Framework versions 1.0 and 1.1, policy is not applied.

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:

  • Other assemblies cannot bind to assemblies that are loaded without context, unless you handle the AppDomain.AssemblyResolve event.

  • Dependencies are not loaded automatically. You can preload them without context, preload them into the default load context, or load them by handling the AppDomain.AssemblyResolve event.

  • Loading multiple assemblies with the same identity without context can cause type identity problems similar to those caused by loading assemblies with the same identity into multiple contexts. See Avoid Loading an Assembly into Multiple Contexts.

  • If a native image exists for the assembly, it is not used.

  • The assembly cannot be loaded as domain-neutral.

  • In the .NET Framework versions 1.0 and 1.1, policy is not applied.

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:

  • The Assembly.LoadWithPartialName method might load a different assembly with the same simple name. For example, two applications might install two completely different assemblies that both have the simple name GraphicsLibrary into the global assembly cache.

  • The assembly that is actually loaded might not be backward-compatible. For example, not specifying the version might result in the loading of a much later version than the version your program was originally written to use. Changes in the later version might cause errors in your application.

  • The assembly that is actually loaded might not be forward-compatible. For example, you might have built and tested your application with the latest version of an assembly, but partial binding might load a much earlier version that lacks features your application uses.

  • Installing new applications can break existing applications. An application that uses the LoadWithPartialName method can be broken by installing a newer, incompatible version of a shared assembly.

  • Unexpected dependency loading can occur. It you load two assemblies that share a dependency, loading them with partial binding might result in one assembly using a component that it was not built or tested with.

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.

Best Practices for Assembly Loading的更多相关文章

  1. error——Fusion log——Debugging Assembly Loading Failures

    原文 So...you're seeing a FileNotFoundException, FileLoadException, BadImageFormatException or you sus ...

  2. .NET:CLR via C# Assembly Loading

    基础知识 Internally, the CLR attempts to load this assembly by using the System.Reflection.Assembly clas ...

  3. Load ContextCLR 探测

    目录 背景Load ContextCLR 探测过程弱签名程序集的探测过程强签名程序集的探测过程Default ContextLoad-From ContextNo ContextRelfection- ...

  4. .NET:鲜为人知的 “Load Context”

    背景 任何一门语言都要了解其类型加载过程,如:Java 的 Class Loader,NodeJS 的搜索方式等,本文概述一下我对 CLR 如何加载程序集,重点说一下 Load Context. 其编 ...

  5. .NET 的程序集加载上下文

    原文:.NET 的程序集加载上下文 我们编写的 .NET 应用程序会使用到各种各样的依赖库.我们都知道 CLR 会在一些路径下帮助我们程序找到依赖,但如果我们需要手动控制程序集加载路径的话,需要了解程 ...

  6. hook mono实现Assembly.Load从指定路径读取文件

    mono-unity github: https://github.com/Unity-Technologies/mono/blob/unity-staging/mono/metadata/assem ...

  7. .NET 介绍

    In order to continue our effort of being modular and well factored we don’t just provide the entire ...

  8. 【.Net Framework 体积大?】不安装.net framework 也能运行!?原理补充-3

    继续补充点吧.接上一篇,我们实现了.net framework的精简的步骤. 有网友评论了,那个核心的 mscoree.dll 从.net framework 2.0开始,微软开始了新的CLR承载模型 ...

  9. 2017 .NET 開發者須知

    筆記-Scott Hanselman 的 2017 .NET 開發者須知 转载http://blog.darkthread.net/post-2017-01-16-dotnet-dev-should- ...

随机推荐

  1. JavaScript字符串相关

      嘛,开头来个定义好了! 首先它是JavaScript基本数据类型之一.字符串由零或多个16位Unicode字符组成的字符序列,用''或者""表示. 它有一些转义序列,例如\n ...

  2. centos下etcd集群安装

    先仔细了解学习etcd 官方: https://github.com/etcd-io/etcd https://www.cnblogs.com/softidea/p/6517959.html http ...

  3. 声明式开发 & 命令式开发

    何为声明式开发,何又为命令式开发~~~ 这里我不做太多概念的剖析,我们只要明确一个: 声明式开发只是告诉计算机需要什么,而不是把每一步都计划好:典型代表为React: 命令式开发则是每一步明确的去操作 ...

  4. [Unity][安卓]Unity和Android Studio 3.0 交互通讯(1)Android Studio 3.0 设置

    [安卓]Android Studio 3.0 JDK安卓环境配置(2017.10) http://blog.csdn.net/bulademian/article/details/78387052 [ ...

  5. 3种检测页面是否符合amp标准的方法

    AMP的关键优势不仅仅在于它能让你的页面更快,还在于它的快可以被验证.有几种方法可以验证AMP文档,它们都会产生完全相同的结果,选择最适合您的开发风格的方法.除了AMP的有效性,您可能还想确认您的AM ...

  6. python基础之 time,datetime,collections

    1.time模块 python中的time和datetime模块是时间方面的模块 time模块中时间表现的格式主要有三种: 1.timestamp:时间戳,时间戳表示的是从1970年1月1日00:00 ...

  7. FPC导通阻抗计算

    pc线路板是有导电功能的,那么如何仅适用手工计算出线路的阻值能?那么就需要使用到一个公式: W*R*T=6000 W是指铜箔的宽度单位是密耳mil. T是指铜箔厚度单位是盎司oz. R是指铜箔的电阻单 ...

  8. AIX修改密码

    grid@DB01:/home/grid>su - oracleoracle's Password: 3004-303 There have been too many unsuccessful ...

  9. Cocos Creator cc.Button (脚本事件内容)

    cc.Class({extends: cc.Component,properties: {}, onLoad: function () { var clickEventHandler = new cc ...

  10. 与图论的邂逅03:Lengauer-Tarjan

    回想一下,当我们在肝无向图连通性时,我们会遇到一个神奇的点——它叫割点.假设现在有一个无向图,它有一个割点,也就是说把割点删了之后图会分成两个联通块A,B.设点u∈A,v∈B,在原图中他们能够互相到达 ...