How to Programmatically Add Service Dependencies to an Existing Windows Service Targeting SQL Server


3 views

When working with Windows Services that depend on SQL Server, we often encounter situations where the service starts before SQL Server is fully initialized. This becomes particularly problematic when:

  • The service installation process doesn't include dependency configuration
  • You need to modify dependencies post-installation
  • Working with legacy systems where reinstalling isn't an option

The most reliable method involves modifying the service configuration in the Windows Registry:


Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\YourServiceName]
"DependOnService"=hex(7):53,00,65,00,72,00,76,00,69,00,63,00,65,00,44,00,65,00,\
70,00,65,00,6e,00,64,00,65,00,6e,00,63,00,79,00,4e,00,61,00,6d,00,65,00,00,\
00,00,00

Replace "YourServiceName" with your actual service name and ensure proper null-terminated Unicode string formatting for dependencies.

For automation scenarios, PowerShell provides a cleaner interface:


# Requires administrative privileges
$serviceName = "YourService"
$dependencies = @("MSSQLSERVER", "SQLSERVERAGENT")

$service = Get-WmiObject -Class Win32_Service -Filter "Name='$serviceName'"
$result = $service.Change($null,$null,$null,$null,$null,$null,$null,$null,$dependencies)

if ($result.ReturnValue -eq 0) {
    Write-Host "Dependencies updated successfully"
} else {
    Write-Host "Failed to update dependencies. Error code: $($result.ReturnValue)"
}

For .NET applications, you can use ServiceController:


using System.ServiceProcess;

public class ServiceDependencyManager
{
    public static void AddDependency(string serviceName, string[] dependencies)
    {
        using (ServiceController sc = new ServiceController(serviceName))
        {
            if (sc.ServicesDependedOn.Any(d => dependencies.Contains(d.ServiceName)))
            {
                return; // Dependency already exists
            }
            
            var newDependencies = sc.ServicesDependedOn
                .Select(s => s.ServiceName)
                .Concat(dependencies)
                .ToArray();

            // Requires admin privileges
            ServiceInstaller.SetServiceDependencies(serviceName, newDependencies);
        }
    }
}

// Usage:
ServiceDependencyManager.AddDependency("MyService", new[] { "MSSQLSERVER" });

After modifying dependencies, verify the changes:

  1. Open Services.msc and check the "Dependencies" tab
  2. Use PowerShell: Get-Service -Name YourService -RequiredServices
  3. Test service restart behavior with SQL Server
  • Access Denied: Run tools as Administrator
  • Service Not Found: Verify exact service names with Get-Service
  • Dependencies Not Respected: Check service startup type (Automatic vs Automatic Delayed)

When dealing with Windows Services that rely on other services (like SQL Server), it's common to need dependency management after the initial installation. The standard approach using sc config during installation doesn't help when you don't control the installation process.

Here are the most effective methods I've used in production environments:

Method 1: Using SC.exe Command

The simplest way is through the command line:

sc config "YourServiceName" depend= "MSSQLSERVER"

Important notes:

  • Replace "YourServiceName" with your actual service name
  • The space after depend= is mandatory
  • Multiple dependencies are separated by forward slashes: depend= "Service1/Service2"

Method 2: Direct Registry Modification

For programmatic control, you can modify the registry directly:

using Microsoft.Win32;

void AddServiceDependency(string serviceName, string dependency)
{
    using (RegistryKey key = Registry.LocalMachine.OpenSubKey(
        $@"SYSTEM\CurrentControlSet\Services\{serviceName}", true))
    {
        if (key != null)
        {
            key.SetValue("DependOnService", new string[] { dependency }, 
                RegistryValueKind.MultiString);
        }
    }
}

After making changes, verify them with:

sc qc "YourServiceName"

Look for the DEPENDENCIES section in the output.

  • Always run these operations as Administrator
  • For SQL Server, the service name might be MSSQLSERVER or a named instance like MSSQL$INSTANCE_NAME
  • Changes take effect after the next service restart
  • Consider adding error handling for production code

Here's a complete PowerShell script I've used successfully:

param(
    [string]$ServiceName,
    [string]$Dependency
)

try {
    $service = Get-Service -Name $ServiceName -ErrorAction Stop
    $currentDeps = (sc.exe qc $ServiceName | 
        Where-Object { $_ -match "DEPENDENCIES" }).Split(":")[1].Trim()
    
    if ($currentDeps -notcontains $Dependency) {
        if ($currentDeps -eq "NONE") {
            $newDeps = $Dependency
        } else {
            $newDeps = "$currentDeps/$Dependency"
        }
        
        sc.exe config $ServiceName depend= $newDeps | Out-Null
        Write-Host "Successfully added dependency"
    } else {
        Write-Host "Dependency already exists"
    }
} catch {
    Write-Error "Failed to modify service: $_"
}