Web服务的配置

时间:2014-09-10 08:01:03

标签: .net wcf

我有使用Web Service的WCF应用程序。我有控制台应用程序来托管Web服务:

 ServiceHost host = new ServiceHost(typeof(MyService));
 host.Open();

Web服务连接到数据库,我想将连接字符串存储在配置文件中,以便在不重新编译解决方案的情况下对其进行编辑。

我可以将此连接字符串添加到Web服务的App.config中,但是当我构建Console Hosting Application时,它将拥有您自己的App.config文件。

我可以将连接字符串添加到Console Host Application的App.config,但我不知道如何将参数从Hosting Application传递给Web Service。

将此参数添加到Web服务的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

是的,您将连接字符串传递给ServiceHost类而不必过于烦恼。当您的控制台程序启动时,以通常的方式从app.config文件中获取连接字符串,然后将此值存储在控制台程序的公共类中的公共静态字符串变量中。完成此操作后,您可以从ServiceHost类中从控制台公共类中检索它。

类似的东西:

 //your console program 
 public class WebHostConsole
 {
   private static string sConnectString;
   sConnectString = System.Configuration.ConfigurationManager.AppSettings("dbconn");
   public static string ConnectionString 
   {
     get { return sConnectString; }
   } 
   //rest of the code

  ServiceHost host = new ServiceHost(typeof(MyService));
  host.Open();
 }

然后,在Web服务类的构造函数中,引用WebHostConsole类的ConnectString属性,并且您的Web服务将具有连接字符串的副本。类似的东西:

//your service host class
public class MyService : iMyService
{
   public MyService()
   {
      String _ConnectString = WebHostConsole.ConnectionString;
      //rest of your constructor

   }
}

<强>更新

这在我的代码中的工作方式是我没有引用Web服务功能类,我引用它的接口类。

 ServiceHost host = new ServiceHost(typeof(iMyService));

您可能知道,使用opreration和数据协定定义构建WCF接口类,然后在您的工作代码中实现该接口。在创建ServiceHost时,请在typeOf中引用接口,而不是工作类。这将消除循环引用。