user6216224
user6216224

Reputation:

Debug mono service application

I am currently developing a mono service application on Linux. Now I want to attach the mono debugger to my running service. How can I find the service process? How can I attach the debugger to it?

Greetings

Upvotes: 0

Views: 755

Answers (1)

maki
maki

Reputation: 431

There is an excellent article from Mikael Chudinov explaining it here: http://blog.chudinov.net/demonisation-of-a-net-mono-application-on-linux/

Starting with it as base, I've made a generic base class that will let you dynamically check if the debugger is attached and either let you debug your code or start the mono service as normal when not being debugged.

The base class is:

using System;
using NLog;
using System.ServiceProcess;

public class DDXService : ServiceBase
{
    protected static Logger logger = LogManager.GetCurrentClassLogger();

    protected static void Start<T>(string[] args) where T : DDXService, new()
    {
        if (System.Diagnostics.Debugger.IsAttached)
        {
            logger.Debug("Running in DEBUG mode");
            (new T()).OnStart(new string[1]);
            ServiceBase.Run(new T());
        }
        else
        {
            logger.Debug("Running in RELEASE mode");
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] { new T() };
            ServiceBase.Run(ServicesToRun);
        } //if-else
    }
}

For using this base class, just inherit from it and override the System.ServiceProcess.ServiceBase methods OnStart and OnStop. Place here your Main method to launch the init sequence:

class Service : DDXService
{
    protected override void OnStart(string[] args)
    {
        //Execute your startup code
        //You can place breakpoints and debug normally
    }

    protected override void OnStop()
    {
        //Execute your stop code
    }

    public static void Main(string[] args)
    {
        DDXService.Start<Service>(args);
    }
}

Hope this helps.

Upvotes: 1

Related Questions