Search code examples
c#-4.0wcf-bindingpublish-subscribenettcpbinding

How to pass parameter to function on pub/sub using nettcpbinding


i am newbie to nettcpbinding callback function,

i have scenario where i need to get the result based on the parameter pass ex. messageId and get the result data when publisher publised based on messageId to the subscribe client.

Thanks,


Solution

  • You can do this with the KnownType attribute.

    Your result classes have to inherit from a base class which is decorated with all the possible derived classes:

    [KnownType( typeof( ResultClassOne ) )]
    [KnownType( typeof( ResultClassTwo ) )]
    class ResultBase
    {
      public int MessageId { get; set; }
    }
    
    class ResultClassOne : ResultBase
    {
      ... other properties
    }
    
    class ResultClassTwo : ResultBase
    {
      ... other properties
    }
    

    This will allow all derived classes to be serialized properly.

    Then use the base class in your contract interface:

    ResultBase Method( int messageId )
    

    And in the implementation, pass back instances of the correct derived class:

    public ResultBase Method( int messageId )
    {
      if ( messageId == 1 ) return new ResultClassOne();
      ...