【问题标题】:Generic Type Information Lost during Serialization/Deserialization with protobuf-net使用 protobuf-net 在序列化/反序列化期间丢失通用类型信息
【发布时间】:2017-02-05 10:27:53
【问题描述】:

我正在尝试集成 protobuf-net 和 mediatR。 这个想法是有一个有效负载将到达的端点。 然后我应该反序列化请求消息并将其交给 mediatR,然后它会根据请求消息类型解析到适当的处理程序。

每个请求都继承自 IRequest。 有一个结果基类和许多从它继承的具体类。 喜欢:

[ProtoContract]
[ProtoInclude(10, typeof(CreateUserRequest))]
[ProtoInclude(11, typeof(DeleteUserRequest))]
[ProtoInclude(12, typeof(GetUserRequest))]
[ProtoInclude(13, typeof(UpdateUserRequest))]
[ProtoInclude(14, typeof(IRequest))]


[ProtoInclude(19, typeof(IRequest<Response>))]
[ProtoInclude(20, typeof(IRequest<CreateUserResponse>))]
[ProtoInclude(21, typeof(IRequest<DeleteUserResponse>))]
[ProtoInclude(22, typeof(IRequest<GetUserResponse>))]
[ProtoInclude(23, typeof(IRequest<UpdateUserResponse>))]
public class Request : IRequest<Response>
{
    [ProtoMember(1)]
    public Guid CorrelationId { get; set; }

    [ProtoMember(2)]
    public string Requestor { get; set; }
}


 [ProtoContract]
 public class CreateUserRequest : Request, IRequest<CreateUserResponse>
 {
    [ProtoMember(1)]
    public string UserName { get; set; }
 }


 public class CreateUserResponse : Response
 {
     [ProtoMember(1)]
     public string NewUserName { get; set; }
 }

问题是,当我用 protobuf 序列化对象时,通用信息丢失了。 我正在一个地方进行反序列化(尝试使用反射等)。 我无法反序列化为 IRequest 类型的对象。

有没有办法保留有关泛型参数的信息,以便我可以将我的对象反序列化为 IRequest 类型,而不仅仅是 CreateUserRequest ?

当然,希望我做错了什么?

【问题讨论】:

    标签: protobuf-net mediatr


    【解决方案1】:

    “包含”功能旨在用于类,而不是接口。您所描述的不是受支持的方案,因为它不提供可靠的可重复反序列化选项。基本上,它试图做的是让您解析具体类型;接口并不能真正帮助您做到这一点 - 更糟糕的是,它们使事情变得更加混乱,因为单一类型(在您的模型中的任何地方都没有提到)可以实现这些接口的所有 - 这并没有真正给出机会很大。

    但是,一般信息不会丢失;通过知道你的类型沿着CreateUserRequest 路径,我们已经知道实现了哪些接口——它们直接绑定到类型定义中。

    我仍然对您要执行的操作感到有些困惑,但是:确定序列化路径时,代码不会查看接口。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-15
      • 2012-02-27
      • 1970-01-01
      • 2012-04-26
      • 2011-10-28
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多