简体   繁体   English

WCF可以通过线路保持引用相等吗?

[英]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 假设我正在使用WCF与客户端和服务器之间的共享数据契约DLL WCF,如果我做类似以下的事情

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. 我得到TrueTrueFalse作为我的结果,这意味着bars[0]bars[1]没有指向服务器上的同一个对象。

Am I doing something wrong, or is it impossible to have shared references over WCF? 我做错了什么,或者是不可能通过WCF共享引用?

You have to explicitly tell WCF to preserve references by specifying 您必须通过指定明确告诉WCF保留引用

[DataContract(IsReference = true)]

otherwise reference equality is lost during message construction. 否则在消息构造期间丢失引用相等性。

The DataContact annotations indicate serialization. DataContact注释表示序列化。 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. 请注意,也可能是您的WCF服务在不同的计算机上运行,​​或者至少在不同的进程上运行。 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. 因此,WCF服务和客户端通常甚至不能访问相同的内存空间,这意味着在它们之间共享引用在理论上是不实际的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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