'Visual Studio creates undesired WCF service instance

We have a solution setup approximate to the following (with comments):

  • Client project. Default debugging target.
    • Service reference. Needed to auto-generate the service's API proxy.
    • The custom code (just some form), which instances the service (we don't use an App.config for this)
  • Server project (contains the exposed WCF service)
    • App.config. Needed to fulfill service reference proxy generation via VS UI, and auto-instantiate service host when debugging.
    • WCF service code
  • Service project. Wraps server project and is an installable Windows Service project type.

For proper context, the WCF service class is set up as [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)], meaning the presence of multiple service instances would imply the launch of a whole new app/server process each (important for the following key problem description).

We've recently noticed that when debugging the client, VS automatically creates up to two service instances, right before even any static custom code gets called, and then one is immediately destroyed while the other may last for the whole VS session. Then, our explicit service instantiation eventually happens from our client (which seems to correctly reuse the long lasting instance created above). I confirmed this situation by adding some trial logging in both the service class constructor and destructor, arising outputs like:

New service instance created. Current PID: 9340.
New service instance created. Current PID: 1204.
Service instance destroyed. Current PID: 1204.

As answered in other questions, I tried disabling the server project's WCF option "Init WCF service host when debugging another project in the same solution", but unfortunately this prevents any instance to start at all and thus the client connection fails.

Note that launching our Windows server doesn't trigger this problem at all, and instead creates a single instance each start, as it should. Also, activating "Regenerate service reference" option at our client seems to cause the issue as well, leaving one of the instances active during VS session.

How to prevent extra automatic service instances to happen while debugging our WCF client in VS, other than one as much? Or is it impossible by design?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source