tags:

views:

2176

answers:

5

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?

Thanks in advance for the help.

A: 

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).

Sergiu Damian
A: 

Yeah i get your point over there about the shared resources and why i shouldnt be using them. But in this case my WCF service is talking to Office Communication Server and it needs to setup some endpoints communicating with OCS server and these endpoints always needs to be up and running. So those resources will be started when service will initialize first time and then stay there until iis shutsdown or other event like that happen.

Now How can i get an handle of an instance of ServiceHostBase class to connect to those events?

Lav
+2  A: 

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.

Samuel Kim
+2  A: 

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...

Sergiu Damian
Correct. But bear in mind that building a custom ServiceHostFactory is not difficult at all. It's mostly boilerplate.
Cheeso
A: 

Thanks Guys for the help!

Lav