2012-02-10 29 views
2

我們目前在我們的應用程序中使用protobuf-net,並且我想在反序列化之後注入屬性。Spring.net和protobuf:對象實例化

例如,如果序列化對象有一個名爲DataFactory

namespace Project 
{ 
    [ProtoContract] 
    public class Model 
    { 
     [ProtoMember] 
     public String Name { get; set; } 

     [ProtoIgnore] 
     public IDataFactory DataFactory { get; set; } 
    } 
} 

財產在Spring.config文件,你有你的接口的定義:

<object id="IDataFactory" type="Project.Impl.DataFactory, Project" /> 

我怎麼能說(或準)表示反序列化設置了屬性IDataFactory

這是一個懸而未決的問題,所以請隨時提供意見或建議。

我認爲掛鉤protobuf-net庫的對象實例化器會很棒,因此它使用Spring.NET創建對象並設置屬性。你覺得我能做到這一點?

謝謝!

理想的情況下

我想有一個的DataFactory反序列化protobufSpring.net直接設置。

Model model = Serializer.Deserialize<Model>(stream); 
Assert.IsNotNull(model.DataFactory); 
Assert.IsTrue(model.DataFactory is DataFactory); 
+0

但是,我並沒有完全理解這個問題:protobuf-net支持創建實際「Model」實例的外部工廠方法,以及在序列化/反序列化期間在任意點調用代碼的序列化回調。這些有用嗎? – 2012-02-10 22:33:30

+0

說真的,我不熟悉春天,但我真的很熟悉protobuf網;如果你澄清你的理想場景是什麼,我相信它可以輕鬆完成 – 2012-02-12 20:35:29

+0

嗨,謝謝,我添加了一個我想要做的場景。 – 2012-02-13 15:00:30

回答

3

這基本上是從早期sbohlen的答案的代碼示例。

假設你有以下Spring.Net XML配置文件objects.xml:

<?xml version="1.0" encoding="utf-8"?> 
<objects xmlns="http://www.springframework.net"> 

    <object id="IDataFactory" type="Project.Impl.DataFactory, Project" /> 

    <object id="MyModel" type="MyNameSpace.Model, MyAssembly"> 
    <property name="DataFactory" ref="IDataFactory" />  
    </object> 

</objects> 

然後,你可以這樣做:

public void Main(...) 
{ 
    var ctx = new XmlApplicationContext("objects.xml"); 

    Model mdl; 

    using (var file = File.OpenRead("mymodel.bin")) 
    { 
     mdl = ProtoBuf.Serializer.Deserialize<Model>(file); 
    } 

    ctx.ConfigureObject(mdl, "MyModel"); 

    // mdl.DataFactory will be injected with your idDatafactory instance 
} 
1

這說明一些你可以用它來攔截各種要點

using System; 
using ProtoBuf; 
using ProtoBuf.Meta; 

[ProtoContract] 
class Foo 
{ 
    [ProtoBeforeDeserialization] 
    private void DoThisBeforeDeserializing() 
    { 
     Console.WriteLine("I iz bein deserialized"); 
    } 
    [ProtoAfterDeserialization] 
    private void DoThisAfterDeserializing() 
    { 
     Console.WriteLine("I haz been deserialized"); 
    } 
    private static Foo UseThisToMakeInstances() 
    { 
     Console.WriteLine("I is being created"); 
     // you could use anything you want here - maybe 
     // an IOC/DI-based construction 
     return new Foo(); 
    } 
} 

public static class Program 
{ 
    static void Main() 
    { 
     RuntimeTypeModel.Default.Add(typeof (Foo), true) 
       .SetFactory("UseThisToMakeInstances"); 

     // just using this as a template, so I can use the serializer 
     var obj = new Foo(); 

     // this does a serialize/deserialize pair 
     var clone = Serializer.DeepClone(obj); 
    } 
} 

(存在使用不同的簽名類似的支撐,並傳入:在反序列化步驟上下文等)。通過這三個攔截點(對象創建,反序列化之前,反序列化之後)的組合,在我看來,大多數事情應該是可能的。

+0

嗨,這是一個很好的解決方案,但我沒有模型對象代碼的手,所以我選擇了其他解決方案。 – 2012-02-13 15:26:27

+0

@BaptistePernet只要它有效,我很高興; p – 2012-02-13 16:27:23