如何调试Windows服务托管的WCF服务?
答
- 运行VS以管理模式
- 从调试菜单中选择附加到进程...
- 选择你的服务过程
- 将断点在服务
答
此外,考虑不在开发期间将其托管在Windows SERVICE中。每当我有一个服务,我有一个替代的代码路径来启动它作为一个命令行程序(如果可能与一个/交互式命令行参数等),以便我不会处理服务调试的具体细节(需要停止更换组件等)。
我只打开“服务”进行部署等。调试总是在非服务模式下完成。
答
我发现一个演练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>
你一切就绪。
呃。在开发服务的同时每天执行100次这样的操作,并且您只是浪费了半天的时间重新安装。 – TomTom 2013-01-17 06:08:33
作品像一个魅力:) – FrenkyB 2017-01-20 08:31:15