wcfnettcpbindingwcf-callbacks

How can I callback the client and expose a new Channel with instance context


I'm making a WCF service with netTcpBinding which has a main lobby with multiple chatrooms which the clients can enter. The Lobby class implements ILobby as the service contract.

When a client wishes to enter a room I want to callback the client exposing a new Channel containing the InstanceContext for the room he just entered but after much searching I am doubting that this is possible.

For example on the Service side I might have

class Lobby : ILobby
{
    Dictionary<string, Chatroom> rooms;

    public void JoinRoom(string roomname)
    {
        if (rooms[roomname].TryEnter()) {}
    }
}

class ChatRoom : IChatRoom
{
    public bool TryEnter(string username)
    {
        ILobbyCallback callback =
            OperationContext.Current.GetCallbackChannel<ILobbyCallback>();
        // How do I do this next bit?
        callback.JoinedRoom(pass some instance context here);
        return true;
    }
}

On the client side callback method I want

public void JoinedRoom(InstanceContext for the room on the service side)
{
    // Create a new WCF proxy using above InstanceContext
    // Create a WPF UI for the new room passing the proxy so it can communicate
    // with the room class directly without going via the root service
}

Is this possible? What's the best practice for spawning new classes with their own contracts on the service side? Or do I just have to bundle everything into one massive MyService class and handle everything myself?


Solution

  • You cannot pass instance context as parameter to any operation contract. It doesn't make sense because that context has local scope. It is called "instance context" = it is context of current service instance. In duplex scenario both client and server has its own service:

    Server's service instance context has meaning only on the server. It is not clear what you are trying to achieve (except very complex architecture).

    But is it really needed? When I look at your code I see that one service and one proxy is enough. Also your JoinRoom operation doesn't need to use callback at all, it can be just request response method.