Search code examples
c#.netwcfservicehostself-hosting

Self host WCF ServiceHost object lifetime


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?


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