我将自定义对象传递给WCF服务时重新初始化

时间:2014-12-21 11:10:52

标签: c# wcf datacontract

所以我现在正试图将自定义对象传递给WCF服务。我假设我的格式是正确的,但我可能不会,因为我对WCF服务还不熟悉,但事实并非如此。我的服务代码如下所示

ILetsHost.cs

[ServiceContract(Namespace = "hiThere")]
public interface ILetsHost
{
    [OperationContract]
    Foo doSome(Foo f, int _i);
}

[DataContract]
public class Foo
{
    [DataMember]
    public int i { get; set; }

    public Foo()
    {
        i = 1;
    }

    public Foo(Foo f)
    {
        this.i = f.i;
    }

    public void doSome(int _i)
    {
        i = i + _i;
    }
}

LetsHost.cs

public class LetsHost : ILetsHost
{
    public Foo doSome(Foo f, int _i)
    {
        MessageBox.Show("f.i is: " + f.i.ToString());
        MessageBox.Show("i is: " + _i.ToString());
        Foo a = (Foo)new Foo(f);
        a.i = f.i;
        a.doSome(_i);
        MessageBox.Show("a.i is: " + a.i.ToString());
        return f;
    }
}

主机代码如下所示:

string hostName = Dns.GetHostName();
        string endPoint = "http://" + hostName + ":8000";

        Uri ep = new Uri(endPoint);
        ServiceHost host = new ServiceHost(typeof(HostingServices.LetsHost), ep);

        using (host)
        {
            host.AddServiceEndpoint(typeof(HostingServices.ILetsHost), new BasicHttpBinding(), "Service");
            host.Open();

            Console.WriteLine("Endpoint: " + endPoint + "/Service");
            Console.WriteLine("Press <ENTER> to terminate");
            Console.WriteLine();

            Console.ReadLine();
        }

我所做的是分离我的Host项目和Client项目。然后我继续将ILetsHost.cs项添加(复制)到客户端项目。客户端代码如下所示:

EndpointAddress ep = new EndpointAddress("http://Stean-PC:8000/Service");
        ILetsHost proxy = ChannelFactory<ILetsHost>.CreateChannel(new BasicHttpBinding(), ep);

        Foo a = new Foo();
        a.doSome(2);
        Console.WriteLine("Value before server pass: " + a.i.ToString());

        a = proxy.doSome(a, 3);
        Console.WriteLine("Value after server pass: " + a.i.ToString());

        Console.WriteLine();
        Console.WriteLine("Press <ENTER> to terminate");
        Console.ReadLine();

现在的问题是这个。你看到LetsHost.cs中的第一个消息框,它告诉我,我传递的Foo abject的i值为0.其中它应该具有值3。然后第三个消息框告诉我,我创建的Foo对象(a)的i值为3,但是当它返回到客户端项目时,返回的Foo对象(a)的i值再次为0.不知道我哪里出错了。任何帮助都将不胜感激,谢谢。

0 个答案:

没有答案