Skip to content

How to use polymorphism on return type of grpc code first service? #319

@soroshsabz

Description

@soroshsabz

ITNOA

I want to use polymorphic return type in grpc service with code first approach, but I do not know how to do it?

I have service contract like below

    [ServiceContract]
    public interface IGreeterService
    {
        [OperationContract]
        BaseResponse SayHello(HelloRequest request,
            CallContext context = default);
    }

And I have two derived response like below

public class ResponseA : BaseResponse
{
string foo;
}

public class ResponseB: BaseResponse
{
string bar;
}

my BaseResponse exist in another library, and I do not want (and I can not) to change this library.

public abstract class BaseResponse
{
public string hoo;
}

So finally I want to implement SayHello like below

public class GreeterService : IGreeterService
{

  public BaseResponse SayHello(HelloRequest request, CallContext context = default)
  {
    if (request.Name == "Heelo")
    {
      return new ResponseA() {foo = "Hi", hoo = "Hey"};
    }
    else
      return new ResponseB() {bar = "bye", hoo = "You"};
  }
}

But I do not know how can I say to OperationContract that I have two type for return type?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions