简体   繁体   中英

Can WCF keep reference equality over the wire?

Say you have a few classes defined as

[DataContract]
public class Foo
{
    [DataMember]
    public List<Bar> Bars {get; set;}
}

[DataContract]
public class Bar
{
    [DataMember]
    public string Baz { get; set; }
}

public class Service1 : IService1
{
    public bool Send(Foo foo)
    {
        var bars = foo.Bars;

        bars[0].Baz = "test2";
        return bars[0].Baz == bars[1].Baz;
    }
}

[ServiceContract]
public interface IService1
{
    [OperationContract]
    bool Send(Foo composite);
}

Assuming I am using WCF to WCF with a shared data contract DLL between the client and server, if I do something like the following

static void Main(string[] args)
{
    using (var client = new ServiceReference.Service1Client())
    {
        var bar = new Bar();
        bar.Baz = "Start";

        List<Bar> bars = new List<Bar>();
        bars.Add(bar);
        bars.Add(bar);

        var foo = new Foo();
        foo.Bars = bars;

        Console.WriteLine(bars[0].Baz == bars[1].Baz);

        bars[0].Baz = "test1";
        Console.WriteLine(bars[0].Baz == bars[1].Baz);

        Console.WriteLine(client.Send(foo));

        Console.ReadLine();
    }

}

I get True , True , False as my result which means that bars[0] and bars[1] did not point to the same object on the server.

Am I doing something wrong, or is it impossible to have shared references over WCF?

You have to explicitly tell WCF to preserve references by specifying

[DataContract(IsReference = true)]

otherwise reference equality is lost during message construction.

The DataContact annotations indicate serialization. That is, your object is serialized, passed over the wire, and then re-constituted as a new object on the other end. So no, it's not possible to keep reference equality.

Note that also, presumably, your WCF service is running on a different machine, or at least a different process. So the WCF service and client normally won't even have access to the same memory space, which means that sharing a reference between them is not practical in theory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM