Lav
Lav

Reputation: 1896

How to Create a Listener for WCF ServiceHost events when service is hosted under IIS?

I have a WCF service which will be hosted under IIS. Now I have some resources(Connections) that I create within service constructor. I need to free up those resources when IIS which is hosting the service shuts down or resets. These are not the resources that I will be clearing out every time client disconnects but they are application wide resources which will only free up when the service itself or IIS shuts down.

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

Upvotes: 3

Views: 8376

Answers (3)

Sergiu Damian
Sergiu Damian

Reputation: 1428

Well, I'm out of ideas, but I think that this article contains your answer in the chapter: "Accessing ServiceHost in IIS". It seems you need to build 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 the initialization and destruction...

Upvotes: 3

Samuel Kim
Samuel Kim

Reputation: 3733

You can use the IDisposable pattern with finalizer on the class that holds the resources.

On unload of AppDomain, all objects are finalized and if the object that has reference to the resources (such connections) has a finalizer, the finalizer will be called and you can close / dispose the resources at that point.

Upvotes: 3

Sergiu Damian
Sergiu Damian

Reputation: 1428

The whole point of WCF services and IIS hosting is to achieve scalability and allow easy hosting. Although you could connect to events exposed by the ServiceHostBase class (see here), I would recommend against it and analyzing if you really need those shared resources. The main reasons for asking you to re-think are: shared resources need to be thread safe (IIS can serve many requests simultaneously), so this creates a bottleneck for the scalability of your application and secondly, it's best if your services are stateless, and this includes (I guess) the usage of share resources (or application wide resources).

Upvotes: 0

Related Questions