据我所知,Visual Studio Express没有用于服务的项目模板。这并不意味着您无法使用VSE编写Windows服务,只是您不会有模板来启动。
要创建服务,您只需创建一个正常的控制台应用程序。创建将负责实际服务实现的服务类。它会是这个样子
using System.ServiceProcess;
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
}
protected override void OnStop()
{
}
}
}
那么该服务的启动代码可以进入你的服务的Main
功能。
using System.ServiceProcess;
namespace WindowsService1
{
static class Program
{
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
}
}
这应该给你你的服务的基本框架。您需要的另一件事是添加服务的安装程序,以便它可以作为服务安装。下面应该让你开始,注意我已经注意到了这一点。
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
namespace WindowsService1
{
[RunInstaller(true)]
public class ProjectInstaller : Installer
{
private ServiceProcessInstaller serviceProcessInstaller1;
private ServiceInstaller serviceInstaller1;
public ProjectInstaller()
{
this.serviceProcessInstaller1 = new ServiceProcessInstaller();
this.serviceInstaller1 = new ServiceInstaller();
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
this.serviceInstaller1.ServiceName = "Service1";
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller1,
this.serviceInstaller1});
}
}
}
鉴于上述情况,您应该有足够的搜索范围或要求有关服务创建的更多细节。对于MSMQ监听器,你可以用下面的MSDN文章为出发点
http://msdn.microsoft.com/en-us/library/ms978425.aspx
伟大的示例代码,让我开始在Windows服务,谢谢。 – philfeyn 2010-10-18 04:28:38
有没有其他方法可以安装服务,即使是手动安装?将代码和密码硬编码到代码中运行服务似乎对我来说是不好的做法。 – philfeyn 2010-10-19 02:23:50
@philfeyn,您可以设置ServiceProcessInstaller.Account来选择帐户的类型。如果它设置为ServiceAccount.User并且用户名/密码设置为空,则在安装服务时将提示您输入凭据。您可以使用.NET框架附带的InstallUtil.exe手动安装该服务。 – 2010-10-19 03:21:12