Skip to content

Instantly share code, notes, and snippets.

@rogeralsing
Created November 1, 2015 18:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rogeralsing/b966d18d66349521a228 to your computer and use it in GitHub Desktop.
Save rogeralsing/b966d18d66349521a228 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Akka.Actor;
using Akka.Util;
namespace SerializerPoC
{
internal class Program
{
private static void Main(string[] args)
{
var system = ActorSystem.Create("foo");
var context = new StreamingContext(StreamingContextStates.All, system);
var bf = new BinaryFormatter(new AkkaSurrogateSelector(), context);
var ms = new MemoryStream();
var someClass = new SomeClass
{
SomeProperty = "Kingkong"
};
bf.Serialize(ms, someClass);
ms.Position = 0;
var t = bf.Deserialize(ms);
Console.ReadLine();
}
}
public class AkkaSurrogateSelector : ISurrogateSelector
{
private static readonly ISerializationSurrogate surrogate = new AkkaSurrogate();
public void ChainSelector(ISurrogateSelector selector)
{
throw new NotImplementedException();
}
public ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector)
{
if (typeof (ISurrogated).IsAssignableFrom(type))
{
selector = this;
return surrogate;
}
selector = null;
return null;
}
public ISurrogateSelector GetNextSelector()
{
throw new NotImplementedException();
}
}
public class AkkaSurrogate : ISerializationSurrogate
{
public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
{
var system = context.Context as ActorSystem;
var surrogated = obj as ISurrogated;
var data = surrogated.ToSurrogate(system);
info.AddValue("@", data);
}
public object SetObjectData(object obj, SerializationInfo info, StreamingContext context,
ISurrogateSelector selector)
{
var system = context.Context as ActorSystem;
var x = info.GetValue("@", typeof (ISurrogate)) as ISurrogate;
var res = x.FromSurrogate(system);
return res;
}
}
[Serializable]
public class SomeClass : ISurrogated
{
public string SomeProperty { get; set; }
public ISurrogate ToSurrogate(ActorSystem system)
{
return new SomeSurrogate
{
SurrogateProp = SomeProperty
};
}
}
[Serializable]
public class SomeSurrogate : ISurrogate
{
public string SurrogateProp { get; set; }
public ISurrogated FromSurrogate(ActorSystem system)
{
var someClass = new SomeClass
{
SomeProperty = SurrogateProp
};
return someClass;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment