Justin CI
Justin CI

Reputation: 2741

How to use Interface as [DataMember] in protobuf-net.Grpc.AspNetCore

I'm working on a .NET project where I need to use Protobuf and gRPC for serialization and communication. My classes use interfaces and the [DataContract] attribute. I'm having trouble getting everything set up correctly. Here are the relevant parts of my code:

[DataContract]    
public partial class Config : IConfig
{
    public Config() { }

    [DataMember(Order = 1)]
    public string Header { get; set; } = string.Empty;

    [DataMember(Order = 2)]
    public string Target { get; set; } = string.Empty;  

    [DataMember(Order = 4)]
    public IEnumerable<IFeature> Features { get; set; }                
}

[DataContract]
public partial class Feature : IFeature
{
    public Feature() { }

    public Feature(string name)
    {
        Name = name;
    }

    [DataMember(Order = 1)]
    public string Name { get; set; }

    [DataMember(Order = 2)]
    public bool IsEnabled { get; set; }

    public override string ToString()
    {
        return Name;
    }
}

Please see the Program.cs

ProtoBuf.Meta.RuntimeTypeModel.Default.Add(typeof(IFeature), true).AddSubType(1, typeof(Feature));

// Generate Board Config Proto.
GenerateBoardConfigProto();

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCodeFirstGrpc(options =>
{
    options.EnableDetailedErrors = true;
    
    
});


var app = builder.Build();

// Configure the HTTP request pipeline.
app.MapGrpcService<BoardConfigurationService.Services.BoardConfigurationService>();
app.MapGet("/", () => "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
app.Run();

I have added

ProtoBuf.Meta.RuntimeTypeModel.Default.Add(typeof(IFeature), true).AddSubType(1, typeof(Feature));

Still Im getting error from Post man as

Exception was thrown by handler. ProtoException: No parameterless constructor found for TestAssets.Interface.Configuration.IFeature MissingMethodException: Cannot dynamically create an instance of type 'TestAssets.Interface.Configuration.IFeature'. Reason: Cannot create an instance of an interface.

Upvotes: 0

Views: 59

Answers (0)

Related Questions