【问题标题】:How to Access a connectionstring from another project如何从另一个项目访问连接字符串
【发布时间】:2011-09-09 02:56:30
【问题描述】:

我在 Visual Studio 2010 的解决方案中有两个项目。
项目 1 包含一个 app.config 和一个 ConnectionString

如何从项目 2 访问 ConnectionString

由于他们都使用相同的ConnectionString,我希望我的解决方案中只有一个实例。

【问题讨论】:

  • 第二个项目类型是什么?是类库还是win app还是什么?
  • 如果您的两个项目的性质要求它们具有非常不同的 app.config 文件,则将其中一个与另一个项目链接的解决方案可能不是最佳的。您还可以使用名为不同的自定义 app.config 文件,并使用 System.Configuration 命名空间的正确编码从两者打开它...
  • #Miroprocessor 它们都是类库

标签: c# .net connection-string


【解决方案1】:

您可以add the files as a link 将文件添加到您的项目之一。

Add an Existing Item 用于您要向其中添加文件的项目 - Open 按钮有一个小的向下箭头,如果单击该按钮,您可以选择Add as Link

这会将文件添加为原始位置的链接,这意味着您只有一个物理文件。

【讨论】:

  • 很好,但是这个想法很好地使用了app.config 中的所有设置,但不能使用这些设置中的一个或一些设置或排除某些设置;)。
【解决方案2】:

另一个想法是使用 IoC 容器,例如 Ninject,将连接字符串注入到您需要它的类的构造函数中。这与工厂模式没有什么不同。

注意:您不需要使用实体框架来使用 Ninject。

看到这个帖子: Ninject - binding constructors with arguments / Entity Framework connection string

【讨论】:

    【解决方案3】:

    除了 Oded 回答中建议的文件链接之外,您可以考虑重构您的应用程序以使用包含 DatabaseConnectionFactory 类等的通用数据访问程序集。此程序集将在其设置中包含连接字符串

    【讨论】:

    • #eFloh 感谢您的回答,我最终按照您的建议重写了我的代码。
    【解决方案4】:

    如果您只想分享特定部分(在您的情况下为连接字符串),那么链接对您不起作用。相反,你可以做类似this:

    The solution is to store the connection strings on the web.config of the parent web app. 
    Note that the web site root is also an app, so you can store a web.config in there (i.e. c:\inetpub\wwwroot\web.config) which will be inherited by all apps under it.
    c:\inetpub\wwwroot\web.config -> common configuration. 
    c:\inetpub\wwwroot\app1\web.config -> configuration for app1
    c:\inetpub\wwwroot\app2\web.config -> configuration for app2. 
    
    In the case the default web site root is off limits, you can create a root app to contain all other apps and store the common configuration there. 
    c:\inetpub\wwwroot\myrootapp\web.config-> common configuration. c:\inetpub\wwwroot\myrootapp\app1\web.config -> configuration for app1 c:\inetpub\wwwroot\myrootapp\app2\web.config -> configuration for app2.
    

    【讨论】:

      【解决方案5】:

      如果您的项目 2 有项目 1 的引用,则项目 1 可能有一个暴露了 ConnectionString 属性的类。

      顺便说一句,“类”可能会从 app.config 中读取连接字符串

      【讨论】:

        猜你喜欢
        • 2023-03-16
        • 2021-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多