c# - How to deserialize when only interface is available? -
i have 3 components:
- utility library (processor.dll): knows element library
- element library (ielement): doesn't know library
- app: knows both libraries
app calls processor library , passes class of type:
classa : ielement
classa serialized before being passed processor. processor base library , not know class types such classa. know ielement however. processor deserialize ielement passed it, of type classa.
the issue interface cannot deserialized. processor not know classa , should not. how can reference passed in object in case?
one way handle create serializationbinder implementation loads classa, pass reference instance of binder processor.dll processor.dll can use binder implementation deserialization. allow keep code references classa in app module (the serializationbinder implementation of course have defined in app module).
here's example: given interface in element library
public interface ielement { string dosomething(string param); }
you define processor this:
public class processorclass { private serializationbinder _binder; public processorclass(serializationbinder binder) { _binder = binder; } public string calldosomething(stream s) { var formatter = new binaryformatter(); formatter.binder = _binder; var = (ielement)formatter.deserialize(s); return i.dosomething("the processor"); } }
in example, i'm using very, simple serialization binder. note must defined in app assembly, that's why don't need reference classa
anywhere besides app.
class binder : serializationbinder { //warning: demonstration only, not use in production code public override type bindtotype(string assemblyname, string typename) { return type.gettype("classa"); } }
then bring in app assembly:
var ms = new memorystream(); var formatter = new binaryformatter(); var theobject = new classa(); formatter.serialize(ms, theobject); var processor = new processorclass(new binder()); ms.seek(0, seekorigin.begin); string result = processor.calldosomething(ms);
see this msdn example example of serializationbinder.
Comments
Post a Comment