现在的位置: 首页 > 综合 > 正文

windows Service开发日志三(制作安装包)

2013年10月26日 ⁄ 综合 ⁄ 共 2704字 ⁄ 字号 评论关闭

windows service没有办法双击就运行.它需要一个安装类来辅助.接下来我们要做的,就是给这个服务添加一个安装辅助类.
在project名上右键,添加新项目,选择installer class.vs会自动给我们创建一个安装类.
实际上,你也可以添加一个新类,然后让这个类继承自System.Configuration.Install.Installer.所以,实际上,用c#写一个安装类,实际上就是要写一个继

承自Installer的类.
说到这里打断一下,虽然你可以自己创建windows service类和install类,但是还是建议让vs来给你创建,因为这样除了有清晰的层次关系,还会得到很多自

动生成的代码段.比如说重写的Dispose方法.
安装windows service类,首先需要一个service安装进程,然后在进程中有service的安装,所以,我们需要在这个安装类中创建这两个类.
this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
你可以这样想:ServiceInstaller负责安装windows service,而ServiceProcessInstaller是包裹在外面的一层.
this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this.serviceProcessInstaller1.Password = null;
this.serviceProcessInstaller1.Username = null;
这个来设置安装时的权限,一般选择本地系统账户的,话,就不需要用户名和密码了
this.serviceInstaller1.ServiceName = "notus";
this.serviceInstaller1.Description = "a sample";

serviceInstaller1.StartType = ServiceStartMode.Automatic;
而ServiceInstaller设定的都是和服务本身相关的一些参数,比如启动方式,名字,描述等.
这里的ServiceName要和前面你写的windows service的名字相同.否则会出麻烦.
如果你想在安装的前后做点什么,那就需要进入到事件的操作.ServiceInstaller提供了安装时的一些事件供你使用,比如下面这个:
serviceInstaller1.BeforeUninstall += new System.Configuration.Install.InstallEventHandler(serviceInstaller1_BeforeUninstall);
我们可以给这个事件加个代码,就是确保你在删除服务的时候,该服务是停止的.(如果服务正在运行,而你要删除它,那就会出问题)
 void serviceInstaller1_BeforeUninstall(object sender, System.Configuration.Install.InstallEventArgs e)
        {
            ServiceController con = new ServiceController(serviceInstaller1.ServiceName);
            if (con.Status == ServiceControllerStatus.Running || con.Status == ServiceControllerStatus.StartPending)
            {
                    con.Stop();
            }
        }
还有一点要注意的是,如果要使用那些环境变量,需要按照下面的方法取得:
this.serviceProcessInstaller1.Context.Parameters["SURL"];
这个安装类麻烦了些,因为出现了三个带install的类,最后应该类似于这个样子:
 [RunInstaller(true)]

 public partial class ProjectInstaller : Installer

{
 this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
 this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
 //......
}
如此这般,完成你的安装类.

这样,工作就基本完成了.如果你是用vs自动添加的这两个类,可能会有些小迷惑,因为点击view code,和到里面在点击,会有很多个名字一样的类出现,然后

有的继承了基类,有的没有继承,有的又引用什么的...其实安静下来看,这几个类都是partial的,也就是局部类.不要被vs弄晕.

2.widnows service的安装

vs命令提示符

一种是在vs命令提示符下(注意不是cmd敲出来的那个,而是在开始菜单的vs安装目录下那个)用命令操作
使用这个安装 installutil myservice1.exe
这样删除 installutil /u myservice1.exe
当然,在运行前,你得先定位到myservice1.exe所在的文件夹.

windows安装项目

也可以使用vs提供的制作安装程序的功能,把你的project添加到主输出,就可以安装.
新建peject,在其他那一类中选择setup project,vs会给你创建一个安装项目.
在项目名上右键,add,peojet output(输出),把你的服务project添加进来.然后再在项目名上右键,view,custom action,你会看到有四个类别,分别

是install,commit,rollback,uninstall,在上面右键,add custom action,然后在application folder中找到你的服务project,添加进来.
如此这般(...),完成.
编译,运行,看看效果 :)如果不出意外,你的服务就可以在控制面板的"服务"窗口中找到.

抱歉!评论已关闭.