Self host WCF ServiceHost object lifetime

2.5k views Asked by At

To kick off my WCF service, I use the following:

selfHost = new ServiceHost(typeof(MyServiceClass));
selfHost.Open();

At some point this will create an instance of MyServiceClass. Will it create a single instance or an instance per request?

4

There are 4 answers

2
tom redfern On BEST ANSWER

If you want to restrict it to a single instance you can instantiate your service class outside and the pass the instance into the servicehost:

var myservice = new MyServiceClass();
selfHost = new ServiceHost(typeof(MyServiceClass), myservice); // forces singleton pattern
selfHost.Open();
1
Darin Dimitrov On

By default it's an instance per request but you could change this. For example you could write your own IInstanceProvider and manage the life of the service class yourself.

2
mike On

It will create instance per request. If you want a single instance you could use a static class. Static class exists for the lifetime of the application. They don't get reinstantiated every time there is a call or new WCF connection is made.

0
ErnieL On

All these answers are correct, but they seem more complex than what you are asking. The basics of whether it creates an instance per call, per session, or singleton are controlled by the InstanceContextMode which is an attribute on your service class. Start reading there.