I am using protobuf-net r282 and when I call Serialize I get the InvalidOperationException error message "Only data-contract classes (and lists/arrays of such) can be processed (error processing Object)". At the point where protobuf-net Serializer.Serialize is being called the object in question has been cast to an interface. Is there a way to get around this?
Here's the code:
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using ProtoBuf;
using System;
namespace EventStore.Core
{
public interface Message
{
}
public interface Event : Message
{
Guid Id { get; set; }
int Version { get; set; }
}
[DataContract]
public class InventoryItemCreated : Event
{
[DataMember(Order = 1)]
public Guid Id { get; set; }
[DataMember(Order = 2)]
public int Version { get; set; }
[DataMember(Order = 3)]
public string Name { get; set; }
public InventoryItemCreated(Guid id, string name)
{
Id = id;
Name = name;
}
public InventoryItemCreated()
{
}
}
public class DefaultSerializer
{
private readonly IFormatter formatter = new BinaryFormatter();
public byte[] Serialize<T>(T graph) where T : class
{
if (default(T) == graph)
return null;
using (var stream = new MemoryStream())
{
this.Serialize(graph, stream);
return stream.ToArray();
}
}
public virtual void Serialize<T>(T graph, Stream output) where T : class
{
this.formatter.Serialize(output, graph);
}
public T Deserialize<T>(byte[] serialized) where T : class
{
if (null == serialized || 0 == serialized.Length)
return default(T);
using (var stream = new MemoryStream(serialized))
return this.Deserialize<T>(stream);
}
public virtual T Deserialize<T>(Stream input) where T : class
{
return (T)this.formatter.Deserialize(input);
}
}
public class ProtoBufSerializer : DefaultSerializer
{
public override void Serialize<T>(T graph, Stream output)
{
Serializer.Serialize<T>(output, graph);
}
public override T Deserialize<T>(Stream input)
{
return Serializer.Deserialize<T>(input);
}
}
class Program
{
static void Main(string[] args)
{
ProtoBufSerializer serializer = new ProtoBufSerializer();
InventoryItemCreated item = new InventoryItemCreated(Guid.NewGuid(), "Widget");
byte[] buffer = serializer.Serialize((Message)item);
}
}
}