简体   繁体   English

使用多个项目获取连接字符串C#SQL Server

[英]Getting Connection String With Multiple Projects C# SQL Server

I have a solution with four projects - Project 1, Project 2, etc. Each project has an app.config file. 我有一个包含四个项目的解决方案-项目1,项目2等。每个项目都有一个app.config文件。 I am trying to reference the System.Configuration.ConfigurationManager.ConnectionStrings from Project 4 in a call from Project 1. 我试图在项目1的调用中引用项目4的System.Configuration.ConfigurationManager.ConnectionStrings。

So in Project 1, I have: 因此,在项目1中,我有:

        UtilitiesClass util = new UtilitiesClass();
        string connectionString = util.getConnectionString();

In Project 4, I have a utility: 在项目4中,我有一个实用程序:

public string getConnectionString()
    {
        string cx = System.Configuration.ConfigurationManager.ConnectionStrings["Shared Items.Properties.Settings.ConnectionString"].ConnectionString;
        return (cx);
    }

The error I get is that the connection string is null. 我得到的错误是连接字符串为null。 I have run this from Project 4 independently and it gets the connection string without error. 我已经从Project 4中独立运行了它,它获取了连接字符串而没有错误。

In general you cannot use application configuration readers in anything other than the "entry point project" - ie the project that is loaded by IIS. 通常,除了“入口点项目”(即IIS加载的项目)外,您不能在其他任何应用程序中使用应用程序配置读取器。 Best practise here is to have the "entry point project" read its application settings file and provide that to the rest of the application through some kind of service class. 此处的最佳实践是让“入口点项目”读取其应用程序设置文件,并通过某种服务类将其提供给应用程序的其余部分。

The reason for it being "best practise" is that you can then unit test your subsidiary projects and classes without the dependency of an external file (which of course will only have one set of properties per test deployment). 之所以成为“最佳实践”,是因为您可以然后对子项目和类进行单元测试,而无需依赖外部文件(当然,每个测试部署仅具有一组属性)。 By setting up the parameters at the point of entry - in this case the Test Case, you can simultaneously test many configurations at once. 通过在输入点设置参数(在本例中为测试用例),您可以一次同时测试许多配置。

You can try adding a Resource file (.resx) to a project, add a connection string and change its accessibility to public, so you can use it trough the projects. 您可以尝试将资源文件(.resx)添加到项目中,添加连接字符串并将其可访问性更改为public,以便可以在项目中使用它。 Hope this helps you 希望这对您有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM