我正在使用VS2008。我有一個項目,SystemSoftware
項目,連接數據庫,我們使用L2E
。我有一個RuntimeInfo
類,其中包含一些共享信息。它看起來像這樣:C#,無法理解這個錯誤?
public class RuntimeInfo
{
public const int PWD_ExpireDays = 30;
private static RuntimeInfo thisObj = new RuntimeInfo();
public static string AndeDBConnStr = ConfigurationManager.ConnectionStrings["AndeDBEntities"].ConnectionString;
private RuntimeInfo() {
}
/// <summary>
///
/// </summary>
/// <returns>Return this singleton object</returns>
public static RuntimeInfo getRuntimeInfo()
{
return thisObj;
}
}
現在我增加了一個輔助項目,AndeDataViewer
,爲其創建一個簡單的用戶界面從數據庫中進行測試/驗證目的顯示數據的解決方案。我不想在助手項目中創建另一組Entity Data Model
。我只是將所有相關文件添加爲新助手項目中的鏈接。
在AndeDataViewer
項目,我從上面RuntimeInfo
類,這是從我SystemSoftware
項目作爲鏈接文件類獲得connection string
。在AndeDataViewer
的代碼是這樣的:
public class DbAccess : IDisposable
{
private String connStr = String.Empty;
public DbAccess()
{
connStr = RuntimeInfo.AndeDBConnStr;
}
}
我SystemSoftware
工作正常,這意味着該RuntimeInfo
類沒有問題存在。但是,當我跑我的AndeDataViewer
,聲明內上述構造,
connStr = RuntimeInfo.AndeDBConnStr;
,拋出異常。例外是複製在這裏:
System.TypeInitializationException was unhandled
Message="The type initializer for 'MyCompany.SystemSoftware.SystemInfo.RuntimeInfo' threw an exception."
Source="AndeDataViewer"
TypeName="MyCompany.SystemSoftware.SystemInfo.RuntimeInfo"
StackTrace:
at AndeDataViewer.DbAccess..ctor() in C:\workspace\SystemSoftware\Other\AndeDataViewer\AndeDataViewer\DbAccess.cs:line 17
at AndeDataViewer.Window1.rbRawData_Checked(Object sender, RoutedEventArgs e) in C:\workspace\SystemSoftware\Other\AndeDataViewer\AndeDataViewer\Window1.xaml.cs:line 69
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
....
InnerException: System.NullReferenceException
Message="Object reference not set to an instance of an object."
Source="AndeDataViewer"
StackTrace:
at MyCompany.SystemSoftware.SystemInfo.RuntimeInfo..cctor() in C:\workspace\SystemSoftware\SystemSoftware\src\systeminfo\RuntimeInfo.cs:line 24
InnerException:
我不明白,因爲它看起來很好,但爲什麼有一個例外?當一個類是一個鏈接類時,我們不能訪問靜態變量?鏈接的類應與我認爲的本地類相同。這裏的「鏈接」意味着當我添加文件時,我使用「添加爲鏈接」。
我該如何避免此異常?
EDIT:
我將SystemSoftware的App.config作爲鏈接添加到AndeDataViewer中。然後解決這個問題,但我不喜歡它。如果我已經有App.config,那該怎麼辦?我不想在那裏手動複製連接字符串,因爲「手動」意味着沒有好處。
對於那些有多個項目共享一個數據庫,這個環節可能是helperful當你有麻煩:MetadataException: Unable to load the specified metadata resource
什麼數據類型是'ConfigurationManager.ConnectionStrings'?我假設'Dictionary',但爲什麼你需要從中獲取ConnectionString? –
Powerlord
2010-04-30 17:51:24
至於依賴關係,你可以讓'AndeDataViewer'具有'SystemSoftware'作爲依賴關係,然後通過'SystemSoftware'命名空間訪問它的對象,儘管你還需要公開'RuntimeInfo'來執行它。 – Powerlord 2010-04-30 17:54:49