使用AssemblyInstaller使用自定义服务名称安装服务

时间:2020-02-04 16:26:58

标签: c# service installation .net-assembly

我有一个Windows服务,该服务使用AssemblyInstaller进行安装。 到目前为止,效果很好。

对于测试,我想更改ServiceName以避免冲突。我找不到解决办法。 由于链接是通过Assembly运行的,因此我无法控制WinServiceInstaller。我看不到在其中注入任何东西的方法。 AssemblyInstaller也不允许更改名称。

我的代码:

using (var inst = new AssemblyInstaller(typeof(WindowsService).Assembly, commandLine: null))
{
    IDictionary state = new Hashtable();
    inst.UseNewContext = true;
    try
    {
        inst.Install(state);
        inst.Commit(state);
    }
    catch
    {
        try
        {
            inst.Rollback(state);
        }
        catch (Exception ex)
        {
            logger.Error(m => m(Resource.ExceptionOnRollback, ex.Message, ex.StackTrace));
        }
        throw;
    }
}

这是WindowsService程序集中的类:

[System.ComponentModel.DesignerCategory("Code")]
[RunInstaller(true)]
public class WinServiceInstaller : Installer
{
    public const string ServiceName = "ServiceName";
    private const string DisplayName = "DisplayName";
    private const string Description = "Description";

    private readonly ServiceProcessInstaller process;
    private readonly ServiceInstaller service;

    public WinServiceInstaller()
    {
        process = new ServiceProcessInstaller
        {
            Account = ServiceAccount.LocalSystem
        };
        service = new ServiceInstaller
        {
            ServiceName = ServiceName,
            DisplayName = DisplayName,
            Description = Description,
            StartType = ServiceStartMode.Automatic
        };

        Installers.Add(process);
        Installers.Add(service);
    }

}

我搜索并找到了其他解决方案,但是这些解决方案是直接使用sc.exe或Installutil.exe。我更喜欢干净的C#解决方案。

如何从这里继续?

0 个答案:

没有答案
相关问题