Search code examples
.netcomwindows-services

ServicedComponent hosted in a Windows Service visible from COM


I am migrating an old C++ Windows Service that hosts COM objects. I managed to create a .Net Windows Service and a COM visible Serviced Component, but only in separate projects.

What I need is for our legacy applications to be able to create instances of my new objects via COM interface; these objects shall be hosted in a Windows Service process that can be managed from the "Services" administration tool (started, delay started, paused, resumed, stopped). There are other reasons why it must be a Windows Service:

  • There must be only one system-wide instance of its process at any given time.
  • It must be long-lived, because it holds static data and performs background processing on it.
  • It should be active before the first COM object is instantiated.
  • It should be automatically started by the first COM object is instantiated should it be stopped at that time for any reason.
  • Object instances will run within the service process.
  • Runs with the Network Service identity.
  • Clients will not be upgraded / modified.

All these points were nicely covered by the old "COM Service" construct from Visual C++ 6.0, but with VB.Net Framework 4 I don't know how to do it.

Perhaps I could merge the .Net Windows Service and the Serviced Component somehow, or there might be other ways to expose classes in my Windows Service.

EDIT:

I forgot to mention one important reason I need it to be a standard Windows Service: It must be able to perform some rather lengthy tasks when it is going to be stopped. Clients will entrust the COM objects with tasks to be performed in background. If the service is stopped prematurely, some of these tasks will be left undone. It's OK as long as the service can perform some cleanup procedures (inserts, updates, etc.) which might take anywhere from none to ten or more seconds. It doesn't need to be bullet proof (it won't) but a normal system shut down or a maintenance service stop must not leave unkept things behind.


Solution

  • Since .NET serviced components are libraries that are hosted by COM+ (dllhost.exe, actually), you must implement IProcessInitializer to have process startup and shutdown events.

    To extend the time the Service Control Manager waits for the service to startup, you can use IProcessControlInit, by casting the object from IProcessInitializer.Startup.