martes, 1 de febrero de 2011

.NET: Debug a Windows Service without deploy

Have you ever wanted to debug a windows service without installing it? Well, there is a very easy way to do this. I am going to show it in this post, and maybe we can discuss more "elegant" solutions in future posts.

When you create a Windows Service project, a "Program" class is created, with a Main method, which is the entrance point of your application. This methods calls ServiceBase.Run, passing an array of service classes as arguments, so in theory you can run a number of classes at the same time under the same windows service process.

Now, this ServiceBase.Run method won't work in a debugging environment. How can we achieve this? Using code expansion!

#if (!DEBUG)
    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[] 
    { 
        new MyService() 
    };
    ServiceBase.Run(ServicesToRun);
#else
    MyService service = new MyService();
    service.Initiate();
    System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#endif

Pretty neat huh? DEBUG is a environment variable that is registered within the visual studio environment. You can create your own (we will see them in other post). So, when the DEBUG configuration is used to compile, the code is just like above. But when RELEASE is used, the compiler will check for these # constructions and only compile the code that corresponds, so there is no way the sleep line is going to be called when installed.

Initiate is a public method that you must define. Name it whatever you want, and call it from your OnStart routing within the service class, like following.

protected override void OnStart(string[] args)
{
    Initiate();
}

Have fun debugging!

No hay comentarios:

Publicar un comentario