使windows服务安装名称可配置

有时,我们安装的windows服务可能是个框架,在同一服务器上可能服务于不同的系统,为了使服务名称不冲突,需要把服务名称更改为可配置。 因为ServiceInstaller能直接设置安装服务的名称和描述,所以很容易就能写出下面的代码:

serviceInstaller.ServiceName = ConfigurationManager.AppSetting["ServiceName"];
serviceInstaller.Description = ConfigurationManager.AppSetting["ServiceDescription"];

编译执行安装,可惜抛出了异常,安装失败了。

失败的原因是,执行安装服务的程序是InstallUtil.exe,安装阶段不会自动加载服务的app.config配置文件,只会加载全局的machine.config,需改为手动加载app.config并读取。 确定解决思路后,我写出了下面的代码:

var targetDirectory = AppDomain.CurrentDomain.BaseDirectory;
var configPath = Path.Combine(targetDirectory, "Service.exe");
var config = ConfigurationManager.OpenExeConfiguration(configPath);
serviceInstaller.ServiceName = config.AppSettings.Settings["ServiceName"].Value;
serviceInstaller.Description = config.AppSettings.Settings["ServiceDescription"].Value;

再次编译运行,发现本机上安装成功了:),整个程序打包交给另一个同事在服务器上安装,发现安装过程又出错了。。。 过去看了一下,发现错误的原因是,本机安装时,InstallUtil程序我是放在和服务同一目录,而服务器上的InstallUtil是和服务在不同目录。看来AppDomain.CurrentDomain.BaseDirectory获取到的是InstallUtil的应用程序域目录路径,而不是服务的。 之后使用反射来解决了这个问题,代码如下:

var path = System.Reflection.Assembly.GetExecutingAssembly().Location;
var targetDirectory = System.IO.Path.GetDirectoryName(path);
var configPath = Path.Combine(targetDirectory, "Service.exe");
var config = ConfigurationManager.OpenExeConfiguration(configPath);
serviceInstaller.ServiceName = config.AppSettings.Settings["ServiceName"].Value;
serviceInstaller.Description = config.AppSettings.Settings["ServiceDescription"].Value;
posted @ 2012-01-12 15:42  vento  阅读(459)  评论(0编辑  收藏  举报