萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> .NET 程式設計

VS2012 專案中 Spring.NET 啟動異常排除:移除 app.config startup 區段

在 Visual Studio 2012 專案中引用 Spring.NET 1.3.2 時,啟動拋出異常:Spring.Context.Support.ContextRegistry 的類型初始值設定項引發異常。

問題重現

  • 環境:VS2012、.NET Framework 4.0、Spring.NET 1.3.2、Console Application
  • 錯誤訊息:TypeInitializationException 包裹 ConfigurationErrorsException
  • 耗時排查無果,偶然發現移除 App.config 中特定區段即解決

解決方案

在 App.config 中移除或註解掉 <startup> 區段:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <!-- 移除或註解此區段 -->
  <!--
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
  -->

  <configSections>
    <sectionGroup name="spring">
      <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core" />
      <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
    </sectionGroup>
  </configSections>

  <spring>
    <context>
      <resource uri="config://spring/objects" />
    </context>
    <objects xmlns="https://www.springframework.net">
      <object name="TestDao" type="TSpring.MyDao.TestDao, TSpring.MyDao" />
    </objects>
  </spring>
</configuration>

根因分析

  • Spring.NET 1.3.2 針對 .NET 4.0 執行環境的組態讀取機制與 <startup> 區段的 supportedRuntime 設定存在相容性衝突
  • ContextRegistry 靜態建構子在初始化時嘗試讀取組態,遇到該區段導致拋出例外
  • 移除後,Spring.NET 改用預設執行環境載入,正常運作

驗證步驟

  1. 備份原 App.config
  2. 註解或刪除 <startup>...</startup>
  3. 重新建置並執行專案
  4. 確認 Spring 容器正常初始化、物件可解析

補充說明

  • 若專案必須指定 .NET 版本 (如混合模式組件),嘗試將 supportedRuntime 設為 v2.0.50727 並設定 useLegacyV2RuntimeActivationPolicy="true"
  • 升級 Spring.NET 至較新版本 (2.x+) 可能已修正此問題
  • 此問題僅發生於舊版 Spring.NET + .NET 4.0 + 特定組態結構的組合
copyright © 萬盛學電腦網 all rights reserved