我想在grpc服务中使用多态返回类型,但我不知道如何做到这一点?

我有如下服务合同

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

我有两个如下的衍生响应

public class ResponseA : BaseResponse
{
string foo;
}

public class ResponseB: BaseResponse
{
string bar;
}

我的BaseResponse存在于另一个库中,我不想(也不能)更改这个库.

public abstract class BaseResponse
{
public string hoo;
}

所以最后我想实现SayHello个,如下所示

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"};
  }
}

但我不知道我怎么能对OperationContract说我有两种类型的返回型?

推荐答案

如果您不能更改BaseResponse,则必须手动配置它,例如:

RuntimeTypeModel.Default.Add(typeof(BaseResponse), false)
    // fields of BaseResponse
    .Add(1, nameof(BaseResponse.hoo))
    // sub-types of BaseResponse
    .AddSubType(10, typeof(ResponseA))
    .AddSubType(11, typeof(ResponseB));

这里我假设ResponseAResponseB至少可以改变,即.

[ProtoContract]
public class ResponseA : BaseResponse
{
    [ProtoMember(1)]
    public string foo;
}

如果可能达到isn't,您还需要手动配置them,例如:

RuntimeTypeModel.Default.Add(typeof(ResponseA), false)
    .Add(1, nameof(ResponseA.foo));

Csharp相关问答推荐

PostingAsJsonAschange在从调用的方法返回时给出500错误

EF Core判断是否应用了AsSplitQuery()

. NET Core DB vs JSON模型设计

如何阻止注释被包含在C#release build. exe中

如何使用XmlSerializer反序列化字符串数组?

在发布表单时绑定包含附加(嵌套)列表的对象列表的正确语法是什么

Int和uint相乘得到LONG?

Blazor EventCallback<;MyType<;T>;>;

如何从ASP.NET核心MVC视图和Blazor传递数据

为什么AggregateException的Catch块不足以处理取消?

DateTime ToString()未以指定格式打印

交替的奇数

使用System.Text.Json进行序列化时发生StackOverflow异常

如何允许数组接受多个类型?

单元测试类型为HttpClient with Microsoft.Extensions.Http.Resilience

如何从非异步任务中正确返回TypeResult

将C#类导入到PowerShell

c#在后台实现类型化数组

如何消除Visual Studio错误,因为它不识别集合表达式的新C#12语法?

通过mini kube中的远程调试Pod与从emoteProcessPickerScript中解析错误输出的代码错误进行比较