c# - 如何避免 SerializationException : Type is not resolved for member XXX when testing a component that uses the LogicalCallContext

标签 c# entity-framework configuration nunit appdomain

当 EF 尝试从 App.config 加载信息时,我最近开始在我的单元测试 (NUnit) 代码中遇到以下异常:

System.Runtime.Serialization.SerializationException : Type is not resolved for member [my type name], [my assembly name]

NUnit GUI 运行器和 R# 的 VS 集成运行器都会发生这种情况。这是重现问题的快速单元测试:

[Test]
public void Test()
{
    // adding 
    // ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    // here fixes things, probably because the configuration is cached

    CallContext.LogicalSetData("FooSlot", new Foo()); // removing this line fixes things
    ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // fails with above exception
}

[Serializable] // removing this gives a different exception complaining that Foo is not Serializable
public class Foo // : MarshalByRefObject // this fixes things
{ 
}

使用fusion log viewer,发现失败是由于

FILE_NOT_FOUND HRESULT

错误。基本上,似乎打开配置以某种方式导致发送 Foo 对象 回到原来的 (nunit runner) 应用程序域,然后尝试加载我的程序集但找不到它,因为它不在 bin 文件夹中。事实上,我确认将程序集复制到 NUnit runner bin 文件夹是解决该问题的另一种方法。

在这一点上,似乎使用 MarshalByRefObject 是最好的选择。但是,如果有更好的选择和/或如果有人可以对正在发生的事情和原因提供详尽的解释,我很乐意来到这里。在这里使用 MarshalByRefObject 有什么缺点吗?

这不同于 this question ,因为我已经将 MarshalByRefObject 确定为潜在的解决方案,并且正在尝试更深入地了解问题/了解 MarshalByRefObject 的含义。该帖子的答案只是对 MarshalByRefObject 的标注,没有有用的附加详细信息。

最佳答案

我认为这很好地解释了为什么会出现此错误。

Is it possible to use the logical call context within a unit test in VS 2010?

我搜索了这个有什么好的选项。除了 MarshalByRefObject,我从来没有找到任何答案。那么为什么你应该用它继承你的对象。很好的解释

按值编码

对象仅在创建它们的应用程序域中有效。任何将对象作为参数传递或将其作为结果返回的尝试都将失败,除非该对象派生自 MarshalByRefObject 或标记为可序列化。如果对象被标记为可序列化,则对象将自动序列化,从一个应用程序域传输到另一个应用程序域,然后反序列化以在第二个应用程序域中生成对象的精确副本。此过程通常称为按值编码(marshal)。

这是来源。有助于理解对象序列化概念

https://msdn.microsoft.com/en-us/library/ms973893.aspx

谢谢这个问题,我搜索并学到了好东西。

关于c# - 如何避免 SerializationException : Type is not resolved for member XXX when testing a component that uses the LogicalCallContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22771524/

相关文章:

c# - 是否可以在插入/更新之前在 POCO 中执行操作?

entity-framework - 向表添加索引

c# - DELETE 语句与 Entity Framework 的 SAME TABLE REFERENCE 约束冲突

configuration - 很棒的 WM 4 run_or_raise 函数

java - Spring bean 配置

c# - 告诉任务等到计时器停止

c# - 无法从 Javascript 访问 webmethod

c# - ElasticSearch 7.1删除索引C#API

泛型方法的 c# 单元测试

java - log4j的配置