简体   繁体   English

获取ac#service中的连接字符串

[英]Getting the connection string in a c# service

I'm using VS 2008. 我正在使用VS 2008。

I have a service that needs to be deployed. 我有一个需要部署的服务。 The service won't be used from a .NET client (like a website or Windows client). 该服务不会从.NET客户端(如网站或Windows客户端)使用。 It needs a database connection. 它需要数据库连接。

I initially had a console app that called the service, and the connection string was set in the app.config of the console app. 我最初有一个调用该服务的控制台应用程序,并且在控制台应用程序的app.config中设置了连接字符串。 I want to move the connection string to the service. 我想将连接字符串移动到服务。 So in the web.config that come with the service I put in the following: 因此,在我放入以下服务的web.config中:

<connectionStrings>

     <clear />
     <add name="REConnectionString"
          connectionString="Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=True;"
          providerName="System.Data.SqlClient" />

</connectionStrings>

And in my MyService.svc.cs I have the following: 在我的MyService.svc.cs中,我有以下内容:

private readonly string connectionString = ConfigurationManager.ConnectionStrings["REConnectionString"].ConnectionString;

But when I run the service this value connectionString is null. 但是当我运行服务时,此值connectionString为null。 How do I get this value from the web.config? 如何从web.config获取此值?

I have even added the following but it is also not working: 我甚至添加了以下内容,但它也无法正常工作:

<appSettings>
     <add key="REConnectionString" value="Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=True;"/>
</appSettings>

If I loop through the list of connection string then it keeps on bring back the connection string from the calling app. 如果我遍历连接字符串列表,那么它会继续从调用应用程序返回连接字符串。 Is there no way that the config file can be used? 是否无法使用配置文件?

I will try with something like this: 我会尝试这样的事情:

Configuration config = ConfigurationManager.OpenExeConfiguration("name_of_your_service.exe");
string connectString = config.ConnectionStrings["YourConnectionStringNameHere"];

You should pay attention to the string passed as name of the config file. 您应该注意作为配置文件名称传递的字符串。
It should be the name of an exe or dll not the config file itself. 它应该是exe或dll的名称而不是配置文件本身。 OpenExeConfiguration will open as Configuration object a file named "name_of_your_service.exe.config" OpenExeConfiguration将作为Configuration对象打开名为“name_of_your_service.exe.config”的文件

Details on OpenExeConfiguration 有关OpenExeConfiguration的详细信息

Just found an interesting question here on SO 刚刚在SO上发现了一个有趣的问题

I right clicked on the project and added a setting of type connection string. 我右键单击该项目并添加了类型连接字符串的设置。 And then I retrieve it like: 然后我检索它像:

MyProject.Properties.Settings.Default.MyConnectionString;

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

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