Is there an easier way to step through the code than to start the service through the Windows Service Control Manager and then attaching the debugger to the thread? It\'s ki
I think it depends on what OS you are using, Vista is much harder to attach to Services, because of the separation between sessions.
The two options I've used in the past are:
Hope this helps.
Use Windows Service Template C# project to create a new service app https://github.com/HarpyWar/windows-service-template
There are console/service mode automatically detected, auto installer/deinstaller of your service and several most used features are included.
What I usually do is encapsulate the logic of the service in a separate class and start that from a 'runner' class. This runner class can be the actual service or just a console application. So your solution has (atleast) 3 projects:
/ConsoleRunner
/....
/ServiceRunner
/....
/ApplicationLogic
/....
For routine small-stuff programming I've done a very simple trick to easily debug my service:
On start of the service, I check for a command line parameter "/debug". If the service is called with this parameter, I don't do the usual service startup, but instead start all the listeners and just display a messagebox "Debug in progress, press ok to end".
So if my service is started the usual way, it will start as service, if it is started with the command line parameter /debug it will act like a normal program.
In VS I'll just add /debug as debugging parameter and start the service program directly.
This way I can easily debug for most small kind problems. Of course, some stuff still will need to be debugged as service, but for 99% this is good enough.
Here is the simple method which I used to test the service, without any additional "Debug" methods and with integrated VS Unit Tests.
[TestMethod]
public void TestMyService()
{
MyService fs = new MyService();
var OnStart = fs.GetType().BaseType.GetMethod("OnStart", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
OnStart.Invoke(fs, new object[] { null });
}
// As an extension method
public static void Start(this ServiceBase service, List<string> parameters)
{
string[] par = parameters == null ? null : parameters.ToArray();
var OnStart = service.GetType().GetMethod("OnStart", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
OnStart.Invoke(service, new object[] { par });
}
I use a variation on JOP's answer. Using command line parameters you can set the debugging mode in the IDE with project properties or through the Windows service manager.
protected override void OnStart(string[] args)
{
if (args.Contains<string>("DEBUG_SERVICE"))
{
Debugger.Break();
}
...
}