Question

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?

Was it helpful?

Solution

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();

OTHER TIPS

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.

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top