Search code examples
c#wcfhostingduplex-channel

Access the object which hosts the service


I'm using WCF 4 with C#. I'm using InstanceContextMode set to Single. The instance of the class implementing my contract is created using the constructor which accepts the reference of the object which hosts the service. The service object is passed when the service host is being created and hosted.

Service Implementation Code:

[ServiceBehavior(UseSynchronizationContext = false, 
     InstanceContextMode = InstanceContextMode.Single)]   
public class ServiceImpl : IMyContract
{
   private ServiceHoster _sh;
   ServiceImpl(ServiceHoster sh)
   {
      _sh = sh;
   }

   public string Call(string input)
   {
      ... //Do some processing on the input string

      return _sh.ProcessCall(string input);
   }
}

ServiceHoster Code:

public class ServiceHoster
{
    private ServiceImpl ns;

    ServiceHoster()
    {
       ...
       Start();
    }

    private void Start()
    {
       //Host Service
       ns = new ServiceImpl(this);

        //Instantiate NetTCP service
        _tcpServiceHost = new ServiceHost(ns, new Uri("net.tcp://localhost:8089"));
        _tcpServiceHost.Open();
    }

    private void Stop()
    {
      if(ns != null && ns.State == CommunicationState.Opened)
        ns.Close();
    }

    public string ProcessCall(string input)
    {
       ...
       return result;
    }
}

The problem that I'm facing now is, we need duplex communication between client and server. For duplex connection we need to set InstanceContextMode set to PerSession.

My questions are:

  1. Can I use multiple values for InstanceContextMode some how (which I think is not possible)?

  2. Is there any other way for ServiceImpl object to get hold of the reference of the object which is hosting it?

  3. Is there anything I can do differently to solve the problem?

Thanks.


Solution

  • First off, I don't think you need to do anything about your InstanceContextMode. See this MSDN/WCF forum thread for more information on how you can keep a list of the connected clients: http://social.msdn.microsoft.com/forums/en-US/wcf/thread/463dd4a2-f9db-4773-b373-7dd470e65f90/

    If you still want to go that way, I would suggest that you implement an instance provider (by implementing the IInstanceProvider instance and plug it into the ServiceHost with a behavior of your choice.)

    If you Google for IInstanceProvider, you'll find examples on how it is done - if you use an IoC container, you'll most likely find a WCF integration for it that works this way.