您的位置:首页 > 编程语言 > C#

Windows服务的配置与安装

2016-02-17 14:18 337 查看
因为当前项目需要使用到一个数据中间件,考虑到服务的稳定性与安全性便采用了Windows服务的方式寄宿推送服务。
创建windows服务首先需要新建一个Windows服务控件,位于常规>Windows服务中



修改完名称后单击添加windows服务,打开创建的windows服务控件代码层,我们可以看到如下原始代码:

partial class QuoteService : ServiceBase
{
public QuoteService()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{
}

protected override void OnStop()
{

}
}
windows服务控件创建后默认为我们重写了两个方法,一个为OnStart一个为OnStop,对应的即为我们的services.msc列表里面的启动与停止事件,我们接下来就可以将需要寄宿服务的启动和停止方法填入这两个事件里面,列如:

partial class QuoteService : ServiceBase
{
private ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private QuoteSocket quote;
public QuoteService()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{
InitialService();

quote = new QuoteSocket();
quote.BindQuote("127.0.0.1", 5555);
quote.Start(6666);
}

protected override void OnStop()
{
quote.Stop();
}

private void InitialService()
{
log4net.Config.XmlConfigurator.Configure(new FileInfo(Environment.CurrentDirectory + @"\Config\log4net.xml"));
log.Info("报价中间件启动");
}
}
修改完Windows服务控件中的代码绑定后,我们接下来就需要添加安装程序,我们单击我们之前添加的windows服务类,右击【设计】页面,找到【添加安装程序】然后会自动为我们生成ProjectInstaller.cs的安装配置信息,首先点开serviceProcessInstaller1>属性页面修改account(账户)为LocalSystem,然后点开serviceInstaller1修改Description(描述)为自定义服务描述信息,列如XXX公司服务,修改完成后保存。

完成上面两个步骤就基本完成了一个Windows服务的配置工作,接下来我们需要使用ManagedInstallerClass安装组件将服务安装到系统服务列表中,这里贴出一个通用的安装与卸载的公共类:

public static class SelfInstaller
{
private static readonly string _exePath = Assembly.GetExecutingAssembly().Location;

public static bool InstallMe()
{
try
{
ManagedInstallerClass.InstallHelper(new string[] { _exePath });
}
catch
{
return false;
}
return true;
}

public static bool UninstallMe()
{
try
{
ManagedInstallerClass.InstallHelper(new string[] { "/u", _exePath });
}
catch
{
return false;
}
return true;
}
}


因为windows服务的启动方式和普通的窗体,控制台不同,所以我们需要在项目的Program类中进行判断当前启动的方式否则安装的服务将无法启动,首先判断启动类型是否为windows服务,如果是,则调用服务的方式运行自身的代码块,代码如下:

if ((!Platform.IsMono && !Environment.UserInteractive)//Windows Service
|| (Platform.IsMono && !AppDomain.CurrentDomain.FriendlyName.Equals(Path.GetFileName(Assembly.GetEntryAssembly().CodeBase))))//MonoService
{
RunAsService();
return;
}

static void RunAsService()
{
ServiceBase[] servicesToRun;

servicesToRun = new ServiceBase[] { new QuoteService() };

ServiceBase.Run(servicesToRun);
}


上述代码中的QuteService即为我们之前新建的Windows服务的名称,完成以上全部配置后,我们就可以在需要的地方调用SelfInstaller.InstallMe();进行安装,或者调用SelfInstaller.UninstallMe();卸载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# 中间件 windows服务