【问题标题】:Unity: Fatal Execution Engine Error when resolving a TimeSpanUnity:解决 TimeSpan 时出现致命的执行引擎错误
【发布时间】:2009-12-03 21:16:47
【问题描述】:

我正在尝试使用Unity 解析TimeSpan。执行容器 Resolve 调用会产生 FatalExecutionEngineError

检测到致命的执行引擎错误 消息:运行时遇到致命错误。错误地址位于线程 0x1bb8 上的 0x543c3dc8。错误代码为 0xc0000005。此错误可能是 CLR 或用户代码的不安全或不可验证部分中的错误。此错误的常见来源包括 COM-interop 或 PInvoke 的用户封送错误,这可能会损坏堆栈。

在 DEBUG 中运行测试会导致调试器请求以下文件。

X:\Unity\Src\ObjectBuilder\Strategies\BuildPlan\DynamicMethod\DynamicMethodBuildPlan.cs

它在第 38 行显示以下 ExecutionEngineException

System.ExecutionEngineException 未处理 Message="抛出了“System.ExecutionEngineException”类型的异常。" 内部异常:

测试

[TestClass]
public class Example
{
    private readonly IUnityContainer container = new UnityContainer();

    [TestInitialize]
    public void TestInitialize()
    {
        container.Register<TimeSpan>(new ExternallyControlledLifetimeManager());
    }

    [TestMethod]
    public void Test()
    {
        var expected = new TimeSpan();
        var actual = container.Resolve<TimeSpan>();
        Assert.AreEqual(expected, actual);
    }
}

【问题讨论】:

  • 我知道 Unity 有一些默认的 ctor 选择规则,但我至少应该看到 Unity 异常。
  • 这也发生在其他结构上,例如 DateTime。

标签: .net struct unity-container fatal-error


【解决方案1】:

我不确定您为什么会收到错误消息,但我尝试将类型配置(在您编辑的配置文件中)替换为以下内容。

<instances>
   <add name="MyTimeSpan" type="System.TimeSpan" value="1.02:03:04"  />
</instances>

var duration = container.Resolve<TimeSpan>("MyTimeSpan");

上面应该返回一个持续时间为 1 天 2 小时 3 分钟 4 秒的时间跨度。

(我在 Unity 4.1 中尝试过)

【讨论】:

  • 我执行了container.RegisterInstance&lt;TimeSpan&gt;(TimeSpan.FromSeconds(10)); 并且解决得很好。
【解决方案2】:

解析 TimeSpan 时出现致命的执行引擎错误

我发布了this issue on the Unity CodePlex site。已经回答了。

在当前位中您会得到正确的“InvalidOperationException”。 TimeSpan 有多个构造函数,默认情况下它选择四个参数的一个,然后不知道要提供什么整数。结构实际上没有零参数的构造函数,clr 在幕后“作弊”。

解决方案是告诉 Unity 使用哪个构造函数。

container.Register<TimeSpan>(new ExternallyControlledLifetimeManager(), 
    new InjectionConstructor(0L));

【讨论】:

  • 但我认为注册实例解决方案仍然是正确的。它更准确地解决了在 IoC 容器中使用 TimeSpan 的问题。
猜你喜欢
  • 2011-05-12
  • 1970-01-01
  • 2013-06-28
  • 1970-01-01
  • 2010-09-27
  • 2016-08-11
  • 2023-01-11
  • 2010-10-16
  • 1970-01-01
相关资源
最近更新 更多