如何调试由Windows服务托管的WCF服务?

3

我使用Windows服务托管来托管我的WCF服务...现在当我调用我的服务时,我无法进行调试!我能调试我的服务吗?

4个回答

7
此外,在开发过程中考虑不要将其托管在Windows服务中。每当我有一个服务时,我都有另一种代码路径可以将其作为命令行程序启动(如果可能的话,带有/interactive命令行参数等),这样我就不必处理服务调试的细节(需要停止以替换程序集等)。
我只会在部署等方面使用“服务”。调试始终在非服务模式下完成。

1
所有我的服务代码都放在一个服务类中,然后我可以从控制台应用程序中运行它,并且可以很好地进行调试。 - Moo-Juice
实际上我有一个特殊的包装器,它使用服务类并“手动”启动服务。 ;) 但是概念是相同的。作为服务来调试服务真的很痛苦。 - TomTom

4
  1. 以管理员身份运行VS
  2. 从“调试”菜单中选择“附加到进程”
  3. 选择你的服务进程
  4. 在你的服务中设置断点

哇。如果您在开发服务时每天这样做100次,那么您刚刚浪费了半天的时间重新安装。 - TomTom
运行得非常好 :) - FrenkyB

0
我在这里找到了一个教程here。 它建议向服务添加两个方法OnDebugMode_Start和OnDebugMode_Stop(实际上是公开OnStart和OnStop受保护的方法),因此Service1类将如下所示:
public partial class Service1 : ServiceBase
{
    ServiceHost _host;
    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        Type serviceType = typeof(MyWcfService.Service1);
        _host = new ServiceHost(serviceType);
        _host.Open();
    }

    protected override void OnStop()
    {
        _host.Close();
    }

    public void OnDebugMode_Start()
    {
         OnStart(null);
    }

     public void OnDebugMode_Stop()
     {
         OnStop();
     }
}

然后在程序中像这样启动它:

static void Main()
{
    try
    {
#if DEBUG
        // Run as interactive exe in debug mode to allow easy debugging. 

        var service = new Service1();
        service.OnDebugMode_Start();
        // Sleep the main thread indefinitely while the service code runs in OnStart() 
        System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
        service.OnDebugMode_Stop();
#else
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] 
                           { 
                                     new Service1() 
                           };
        ServiceBase.Run(ServicesToRun);
#endif
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

在 app.config 中配置服务:

<configuration>
<system.serviceModel>
<services>
  <service name="MyWcfService.Service1">
    <endpoint address="" binding="basicHttpBinding" bindingConfiguration=""
      contract="MyWcfService.IService1">
      <identity>
        <dns value="localhost" />
      </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration=""
      contract="IMetadataExchange" />
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8732/Design_Time_Addresses/MyWcfService/Service1/" />
      </baseAddresses>
    </host>
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior>
      <serviceMetadata  httpGetEnabled="True"  policyVersion="Policy15"/>
      <serviceDebug includeExceptionDetailInFaults="True" />
    </behavior>
  </serviceBehaviors>
</behaviors>

一切准备就绪。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接