2013-06-25 42 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" /> 
相关问题