How to create a listener for WCF ServiceHost events when a service is hosted in IIS?

I have a WCF service that will host in IIS. Now I have some Connections that I create in the service constructor. I need to free these resources when the IIS hosting the service is disconnected or reset. These are not the resources that I will clean up every time the client disconnects, but they are wide application resources that will be released only when the service itself or IIS shuts down.

I saw another entry in which someone mentioned that he created a listener to capture ServiceHost events. Can someone help me figure out how to get the ServiceHost handle and capture the IIS reset or IIS shutdown event and free up my resources in the WCF service?

+3
source share
3 answers

Well, I have no ideas, but I think this article contains your answer in the chapter: “Accessing ServiceHost in IIS”. It seems that you need to create your own HostFactory, because out of the box, IIS uses the standard HostFactory and practically controls the creation and destruction of hosts. By providing your own HostFactory, you can add your own code to control initialization and destruction ...

+3
source

You can use the IDisposable template with a finalizer in a class that contains resources.

When unloading the AppDomain, all objects are completed, and if the object that has the link to resources (such connections) has a finalizer, the finalizer will be called, and you can close / delete resources at this point.

+3
source

The whole point of WCF and IIS host services is to achieve scalability and ease of hosting. Although you can connect to events opened by the ServiceHostBase class (see here ), I would recommend against it and analyze whether you really need these shared resources, The main reasons that make you think: shared resources must be thread safe (IIS can serve many requests), so this creates a bottleneck for the scalability of your application, and secondly, it is best if your services do not have a status, and this includes (I think) the use of shared resources (or application resources).

0
source

All Articles