159

I have a Windows Service that makes use of a SQL Server database. I don't have control over the installation of the service, but would like to add a dependency on the service to ensure that it starts after SQL server has started. (SQL server is running on the same machine as the service in question)

Is there a tool to add a dependency or possibly editing the registry directly?

squillman
  • 37,618
  • 10
  • 90
  • 145
Rick
  • 1,735
  • 2
  • 12
  • 6

5 Answers5

234

This can also be done via an elevated command prompt using the sc command. The syntax is:

sc config [service name] depend= <Dependencies(separated by / (forward slash))>

Note: There is a space after the equals sign, and there is not one before it.

Warning: depend= parameter will overwrite existing dependencies list, not append. So for example, if ServiceA already depends on ServiceB and ServiceC, if you run depend= ServiceD, ServiceA will now depend only on ServiceD. (Thanks Matt!)

Examples

Dependency on one other service:

sc config ServiceA depend= ServiceB

Above means that ServiceA will not start until ServiceB has started. If you stop ServiceB, ServiceA will stop automatically.

Dependency on multiple other services:

sc config ServiceA depend= ServiceB/ServiceC/ServiceD/"Service Name With Spaces"

Above means that ServiceA will not start until ServiceB, ServiceC, and ServiceD have all started. If you stop any of ServiceB, ServiceC, or ServiceD, ServiceA will stop automatically.

To remove all dependencies:

sc config ServiceA depend= /

To list current dependencies:

sc qc ServiceA
Kip
  • 3,390
  • 3
  • 22
  • 14
  • I had originally select the answer indicating how to edit the registry. But using the SC command is more in line with what I was looking for. Thx. – Rick Jan 29 '11 at 21:54
  • 7
    If you want to see the existing dependencies before changing them with Kip's method, you can type sc qc YourServiceName – mivk Oct 01 '11 at 17:43
  • 1
    Just be careful... I just used this and didn't realize that it will overwrite existing dependencies.. there were two for my service that I don't remember.. now they're gone.. oh well! So make sure you run the command @mivk mentioned first to see any other dependencies first. – Matt Mar 28 '13 at 15:49
  • @Matt good point, i will add a warning. – Kip Mar 29 '13 at 17:55
  • 1
    You can query currently configured dependency for a service by using `sc qc [service name]` command – gerrytan Aug 27 '13 at 06:57
  • Does setting up a dependency like this actually work though (with respect to SQL Server)? I've set it up and the service is still attempting to access SQL server before it is ready -- I am not the only one, see: http://stackoverflow.com/questions/8556808/how-can-i-make-nservicebus-host-based-windows-service-wait-for-sql-server-to-sta – mikey Aug 28 '13 at 17:29
  • @mikey i've been using this to ensure that SQL Server starts before Tomcat for several years. I'm not sure what is going on in your case--maybe the SQL Server service tells the OS that it is "started" before it is fully initialized? – Kip Aug 29 '13 at 14:34
  • @Kip Yes that is what I've gathered, a service "start" event should return quickly -- so service developers will often fire off asynchronous threads and return success/failure right away. In my case, the very first thing the custom service did was establish a connection to the DB. It was trying to connect too soon, even with the dependency (and not failing, just stopping). I was able to work around this by scheduling a batch file which waits 30 seconds and starts the service. On newer operating systems I was able to select "Automatic [Delayed]" for the service and that works great as well. – mikey Aug 29 '13 at 14:41
  • For completeness, if you want to depend on a SQL Server instance, you have to use its name this way: MSSQL$SQL2008 (if is a SQL 2008) or MSSQL$SQL2005 (if it is SQL 2005). Do not use its "display name" ;-) – Andrea Antonangeli Mar 15 '14 at 16:40
  • 4
    If like me, your Service has spaces in the name, enclose it in quotes. – Lazlow Mar 18 '14 at 08:46
  • 8
    If using powershell, make sure you use `sc.exe` otherwise you will get error: 'A positional parameter cannot be found that accepts argument' – spuder Apr 17 '15 at 23:42
  • I didn't need a space after the equals sign on Windows Server 2012? – Nick Jul 03 '16 at 21:39
  • 1
    Use "sc query | findstr SERVICE_NAME" to get the running services names – Sabin Neagu Sep 17 '16 at 07:46
43

You can add service dependencies by adding the "DependOnService" value to the service in the registry using the regedit command, services can be found under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\<Service name>. The details can be found at MS KB article 193888, from which the following is an excerpt from:

To create a new dependency, select the subkey representing the service you want to delay, click Edit, and then click Add Value. Create a new value name "DependOnService" (without the quotation marks) with a data type of REG_MULTI_SZ, and then click OK. When the Data dialog box appears, type the name or names of the services that you prefer to start before this service with one entry for each line, and then click OK.

Kyle Brandt
  • 82,107
  • 71
  • 302
  • 444
pauska
  • 19,532
  • 4
  • 55
  • 75
  • 8
    Holy Cow! That was the fastest answer I've ever received. I barely got back to the home page. – Rick Jun 12 '09 at 14:55
3

I was looking for a purely PowerShell (no regedit or sc.exe) method that can work on 2008R2/Win7 and newer, and came up with this:

Easy one is do the regedit with PowerShell:

Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\LanmanWorkstation' -Name DependOnService -Value @('Bowser','MRxSmb20','NSI')

Or, using WMI:

$DependsOn = @('Bowser','MRxSmb20','NSI','') #keep the empty array element at end
$svc = Get-WmiObject win32_Service -filter "Name='LanmanWorkstation'"
$svc.Change($null,$null,$null,$null,$null,$null,$null,$null,$null,$null,$DependsOn)

The Change method of the Win32_Service class helped point to a solution:

uint32 Change(
[in] string  DisplayName,
[in] string  PathName,
[in] uint32  ServiceType,
[in] uint32  ErrorControl,
[in] string  StartMode,
[in] boolean DesktopInteract,
[in] string  StartName,
[in] string  StartPassword,
[in] string  LoadOrderGroup,
[in] string  LoadOrderGroupDependencies[],
[in] string  ServiceDependencies[]
);
JoeGasper
  • 31
  • 1
1

I wrote a simple .net application to manage service dependencies, if you are interested. It's free.

http://webpages.charter.net/bushman4/servicedependencymanager.html

Glenn Sullivan
  • 1,368
  • 9
  • 17
  • 1
    It is telling me I need .NET 1.1 but I am running windows 7 – Nick Jun 17 '14 at 17:41
  • 1
    .Net 1.1 needs to be installed on Windows 7. See the answer to this question: http://answers.microsoft.com/en-us/windows/forum/windows_7-windows_programs/how-to-install-net-framework-11-in-windows-7-64/eb1e6232-e874-432e-ab43-17660e25e43d – Glenn Sullivan Jun 18 '14 at 18:29
  • 10
    Really, in 2014 you were recommending installing .NET 1.1 on Win7 instead of just recompiling it for 4.0? Thanks, no. – Endrju Jul 03 '15 at 21:43
1

In C++ (ATL) I did like this

bool ModifyDependOnService(void)
{
  CRegKey R;
  if (ERROR_SUCCESS == R.Open(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\services\\MyService"))
  {
    bool depIsThere = false;

    // determine if otherservice is installed, if yes, then add to dependency list.
    SC_HANDLE hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
    if (hSCManager)
    {
      SC_HANDLE hService = OpenService(hSCManager, L"OtherService", SERVICE_QUERY_STATUS);
      if (hService)
      {
        depIsThere = true;
        CloseServiceHandle(hService);
      }
      CloseServiceHandle(hSCManager);
    }

    std::wstring key = L"DependOnService";
    if (depIsThere )
    {
      const wchar_t deps[] = L"RPCSS\0OtherService\0";
      R.SetValue(key.c_str(), REG_MULTI_SZ, deps, sizeof(deps));
    }

    R.Close();
    return true;
  }
  return false;
}
AndersK
  • 111
  • 2
  • though your appproach works, there is an official way for querying/changing a service's configuration using [QueryServiceConfigA](https://docs.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-queryserviceconfiga) and [ChangeServiceConfigA](https://docs.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-changeserviceconfiga) – AntonK Nov 10 '21 at 20:57