Windows Services Using Delphi for .Net

Well, today I begin my foray into Delphi for .Net. I need to be able to communicate with the MyFax site using SOAP. Since Delphi 5 doesn’t do SOAP out of the box, I decided to try .Net. But first I need to be able to write a Windows service in .Net. Oh Joy!

The first thing that I had to learn was how to reference a .Net class in Delphi. First you have to Project Add Reference and select the unit that you need. For reasons that are not clear to me at the moment, this step doesn’t seem to be true for all units. Then you have to reference that unit on the uses clause in the program.

The next thing that I discovered was that the ServiceBase class does not automatically create the work thread like the old Delphi TService classes did. So the OnStart event is just that. It needs to execute the services initialization code, which includes creating and starting the worker thread. Obviously, by extension, the OnStop event holds the service shutdown code, which must include the the code required to stop the worker thread. There are two ways to do that; set a property to tell the thread to stop or call Thread.Abort which will raise a ThreadAbortException in the thread.

Setting up the Installer class to allow the service to be self-installing proved to be more of a challenge that expected as well. It turns out that the Delphi linker removes unreferenced classes from the assembly. Since the Installer class is indeed unreferenced, but it is only used by the installutil.exe utility, the linker cheerily removed if from the assembly and installutil.exe couldn’t find it. To get around this problem I needed to add the following line to the source file:

[assembly: RuntimeRequiredAttribute(TypeOf(TMyInstaller))]

This tells the linker to leave the unreferenced class, in this case, TMyInstaller, in the assembly.

Comments are closed.