2013-06-25 56 views
3

我怎麼從app.config中連接字符串中的另一個「類庫項目」如何從另一個類庫項目中的app.config獲取連接字符串?

在同一個類庫,我可以使用此代碼:

DAL.Properties.Settings.Default.BayrueConnectionString; 

但問題是,我不能從我的網絡應用程序獲取它。

感謝 enter image description here

+1

類庫使用使用它們的應用程序的配置文件,這樣的設置必須在應用程序的配置文件,而不是庫。庫不使用配置文件。 – Tim

+0

正如你所看到的,我正在使用app.config – HAJJAJ

+0

可能重複[.net app.config庫項目](http://stackoverflow.com/questions/1742929/net-app-config-in-library-project) – Steve

回答

3

我覺得有沒有更優雅的方式莫過於此。向你的類庫中添加一個靜態幫助器方法,它返回它。

public sealed class Helper 
{ 
    private Helper() 
    { 
    } 

    public static string GetBayrueConnectionString() 
    { 
     return DAL.Properties.Settings.Default.BayrueConnectionString; 
    } 
} 
+0

我認爲這個會解決它。 – HAJJAJ

0

添加參考System.Configuration

使用System.Configuration.ConfigurationManager.ConnectionStrings["DAL.Properties.Settings.BayrueConnectionString"]

+0

未將對象引用設置爲對象的實例。 這是我在使用代碼時遇到的錯誤 – HAJJAJ

+0

您確定app.config文件位於運行應用程序的文件夾中嗎? –

+0

app.config在另一個項目中 – HAJJAJ

0

首先,在您想要引用的項目中創建一個新的ConnectionStrings.config文件。

ConnectionStrings.config:

<connectionStrings> 
    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data      Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MvcApplication-20130625013234;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MvcApplication-20130625013234.mdf" /> 
</connectionStrings> 

接下來,卸載您的DAL項目。卸載後,右鍵單擊>編輯DAL.csproj。

以下元素添加到的.csproj與包括= 「{你想的ConnectionStrings.config引用}」:

<ItemGroup> 
    <Content Include="..\ConnectionStrings.config" /> 
</ItemGroup> 

Solution Explorer

刷新您的項目。這應該將ConnectionStrings.config文件(如上所示)添加到您的項目中。注意兩者都會打開同一個文件。現在編輯的app.config引用剛添加到您的DAL新創建的config文件:

<connectionStrings configSource="ConnectionStrings.config" /> 
相關問題