0

Say I have a service like the following

[ServiceBehavior(
    InstanceContextMode = InstanceContextMode.Single,
    ConcurrencyMode = ConcurrencyMode.Multiple
)]
class MyService { ... }

Is it then OK to provide a single instance to multiple ServiceHosts? Like:

var serviceInstance = new MyService();
var host1 = new ServiceHost(serviceInstance);
host1.AddServiceEndpoint(...);
var host2 = new ServiceHost(serviceInstance);
...

In the existing codebase, this service is being used from a single ServiceHost only. However, the ConcurrencyMode is Multiple, i.e.

The service instance is multi-threaded. No synchronization guarantees are made. Because other threads can change your service object at any time, you must handle synchronization and state consistency at all times. being used

Meaning it already had to be thread safe, and from the thread safety angle, providing it to multiple ServiceHosts looks fine.

Any other objections?

Evgeniy Berezovsky
  • 18,571
  • 13
  • 82
  • 156

1 Answers1

1

As long as you aren't keeping any variables that change state of your service during its lifetime, there is no problem.

Radu Pascal
  • 1,275
  • 14
  • 18
  • Have you done this before, or is there anything in the way `ServiceHost` works that makes you think this is OK and that you could elaborate on a bit, so that I don't have to rely on taking your word for it? – Evgeniy Berezovsky Apr 07 '14 at 05:40
  • 1
    We're doing something similar for a bridge service. Basically it has a service that is binded to multiple protocols. Whenever a client calls a service method, the data is just placed on another bus. The object for putting the data on the bus is instantiated on each call. Because between the calls no information is shared, there is no problem. – Radu Pascal Apr 07 '14 at 06:43
  • +1 Thanks for sharing your experience. Useful - and also necessary, unless and until your karma approaches that of [Chuck Norris](http://stackoverflow.com/users/22656/jon-skeet) and your word is enough ;) – Evgeniy Berezovsky Apr 07 '14 at 07:18