Enabling Windows Service Injection
Is there a way to set the dependency of one "myWindowsService" to another service running on the same machine, such as "SqlService"?
The problem is that you don't know the name of the "sql service" where "myWindowsService" will be installed, but my service depends on the fact that sql is already running.
thanks
Edit: Didn't read the question correctly.
A workaround (not the most elegant solution) is to list all services with a known whitelist with known instance names.
Using ManagementObject you can install dependencies (but you must know the name of the service):
bool SetServiceDependencies(string serviceName, string[] dependencies)
{
try
{
string objPath = string.Format("Win32_Service.Name='{0}'", serviceName);
//Uses lazy initialization
ManagementObject mmo = new ManagementObject(new ManagementPath(objPath));
//Get properties to check if object is valid, if not then it throws a ManagementException
PropertyDataCollection pc = mmo.Properties;
}
catch (ManagementException me)
{ //Handle errors
if (me.ErrorCode == ManagementStatus.NotFound) {
//Service not found
}
return false;
}
try
{
object[] wmiParams = new object[11]; //parameters for Win32_Service mmo object Change-parameters
wmiParams[10] = dependencies;
//Should we remove dependencies, use array containging 1 empty string
if (dependencies == null || dependencies.Length == 0)
{
wmiParams[10] = new string[] { "" };
}
//Change dependencies
string returnStatus = mWmiService.InvokeMethod("Change", wmiParams).ToString();
}
catch (Exception)
{
return false;
}
return true;
}
a source to share
If you are using
sc create <service>
you can provide other services to do this so that your installed service depends on that service to start.
sc create <service> depend= mssqlserver
This can also be done automatically if you use the ServiceInstaller classes. There is an area in the properties of this controller that defines the launch dependencies.
I know you said you might not know the name of the other services, but changing the dependencies is also pretty straightforward.
a source to share