调试 Windows 服务而不部署它






4.85/5 (23投票s)
本文介绍了一种无需部署即可轻松调试 Windows 服务的方法。

引言
最初,使用 Visual Studio 和 .NET Framework 构建 Windows 服务并不容易。 现在 Microsoft 已将此功能集成为模板和类库,这变得容易得多。 这很好,但是要测试新创建的服务,您必须部署它。 这意味着您必须添加安装程序并构建整个 MSI 文件并在您的环境中运行它。 部署后,您可以使用 Windows 服务控制器启动它,并将调试器附加到它。
我不知道这对您来说听起来如何,但对我来说,进行快速测试需要做太多的不必要的工作。 本文介绍了一种更容易的方法。
Using the Code
您将找到一个使用此概念的示例应用程序。 这是它的工作方式。
首先,您需要一个可用的 Windows 服务。 (有关更多信息,请参阅这里。)
在 Visual Studio 中,构建 Web 服务很容易。 创建一个新项目并选择 Windows 服务模板。
然后将ServiceDebuggerHelper
项目添加到您的解决方案并对其进行引用。 您可以在示例代码中找到它。
默认情况下,当您创建 Windows 服务项目时,Visual Studio 将创建两个类:一个Program
类和一个Service1
类。 这是 Program 类的样子
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun = new ServiceBase[] { new Service1() };
ServiceBase.Run(ServicesToRun);
}
}
我们首先要做的是用条件语句包围该代码,以便我们可以控制我们是否要作为真正的服务运行或仅在调试模式下运行。
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
if (args.Length > 0 && args[0].ToLower().Equals("/debug"))
{
Application.Run(new ServiceRunner(new Service1()));
}
else
{
ServiceBase[] ServicesToRun = new ServiceBase[] { new Service1() };
ServiceBase.Run(ServicesToRun);
}
}
}
在这个新的Program
类中,ServiceRunner
将充当服务主机。 为了使其工作,您必须在项目属性中添加“/debug
”命令行选项。
转到项目 -> ... 属性 -> 调试,然后在命令行参数字段中键入 /debug。
从那里,您有两种方法使您的服务可调试。 您可以实现IDebuggableService
或从DebuggableService
基类继承。
实现 IDebuggableService 接口
如果您已经子类化了ServiceBase
并将该子类用于所有服务,或者您只是想完全控制实现,则应实现IDebuggableService
接口。 这是它的定义
public interface IDebuggableService
{
void Start(string[] args);
void StopService();
void Pause();
void Continue();
}
请注意,stop
方法称为StopService
,以避免与ServiceBase
类的现有Stop
方法冲突。
这是此接口的示例实现
public partial class Service1 : ServiceBase, IDebuggableService
{
//
// Your existing service code
//
// ...
//
#region IDebuggableService Members
public void Start(string[] args)
{
OnStart(args);
}
public void StopService()
{
OnStop();
}
public void Pause()
{
OnPause();
}
public void Continue()
{
OnContinue();
}
#endregion
}
子类化 DebuggableService
从DebuggableService
子类化您的服务甚至更简单。 您所要做的就是将基类从ServiceBase
更改为DebuggableService
。
public partial class Service1 : DebuggableService
{
//
// Your existing service code
//
// ...
//
}
所有控制方法都已由DebuggableService
实现。
关注点
在我的示例代码中,我添加了一个 Windows 窗体类,让您可以启动、停止和暂停您的服务。 您可以按原样使用它,构建您自己的控制器界面,或者只是在您的程序类中调用这些方法。 由你决定。
当然,您仍然应该部署您的服务以进行最终的测试运行。 这样做的一个好理由是测试您的服务将在其中运行的实际安全上下文。 它不会具有与您在 Visual Studio 中运行时相同的权限,但此技术可以加快开发过程。