Restarting a Failed Service

I have an application hosted inside a Windows service that needs to be continuously running. Occasionally the application service host will fail and I have to restart the service. How can I automatically restart a failed service host?

You may not find the advice I have to give here particularly helpful, but there are two important points that I'd like to get across.

The first piece of advice is that there's no direct way to simply "restart" a service host. As pointed out in the communication lifecycle, once an object becomes faulted, it is dead and there's no way to bring it back to life. Instead, the only way to recover from a faulted service host is to abort the old one and throw it away. Then, you'll be able to create a new service host as a replacement to take over. You can hook the Faulted event on the service host to find out when you need to do this.

The second piece of advice is that managing applications for continuous operation is very challenging. It is possible to build a host that will cleanly restart an application whenever necessary but you will spend a lot of time working on the host and not much time working on your application. IIS to a large extent is just a tool for starting, stopping, and restarting applications on demand. If that's the feature set you need, then why expend a lot of effort creating a new hosting environment that isn't going to be as good? There may be some bad reasons for choosing IIS as your hosting environment, but needing hosted application management is not one of them.

Next time: Faking Channel Security