WCF服务似乎无法将对象返回到表单应用程序

时间:2017-06-07 14:26:37

标签: c# winforms visual-studio wcf object

我正在尝试使用Windows窗体应用程序作为客户端在Visual Studio中创建WCF服务。

问题是我在调用方法时似乎无法从我的服务接收数据(我希望得到客户的对象返回) - 数据必须存储在服务中,没有数据库。 (这可能吗?没有数据库?)

这是MyService.cs:

 public class MyService : IMyService
{
    Store store = new Store();

public void RegisterCustomer(string name, string pass)
    {
        Customer c = new Customer(name, pass);
        store.Customers.Add(c);
    }

  public Customer GetCustomer(string name)
    {
        Customer c = new Customer();
        foreach(Customer i in store.Customers)
        {
            if (i.UserName.Equals(name))
            {
                c = i;
            }                    
        }
        return c;           
    }

操作和数据成员在IMyService接口

中声明
namespace WcfService
{
[ServiceContract]
public interface IMyService
{
 [OperationContract]
    // register - klant bestaat niet --> voeg toe aan klantenlijst -1.1-
    void RegisterCustomer(string name, string pass);

 [OperationContract]
    // login - klant bestaat niet --> voeg toe aan klantenlijst
    Customer GetCustomer(string name);

 [DataContract]
public class Customer
{
    string username;
    string password;
    int saldo;

    [DataMember]
    public string UserName { get{ return username; }set{ username = value; }
    }

    [DataMember]
    public string Password{get { return password; }set { password = value; }
    }

    [DataMember]
    public int Saldo{get { return saldo; }set { saldo = value; }
    }
    public Customer() { }

    public Customer(string name, string pass)
    {
        this.username = name;
        this.password = pass;
        this.saldo = 100;
    }
}

我们在form1:form

中的引用
//reference
    ServiceReference1.MyServiceClient client = new ServiceReference1.MyServiceClient();

调用服务的表单应用

private void button2_Click(object sender, EventArgs e)
    {
        string name = textBox4.Text;
        string pass;

        if (client.CustomerExists(name))
        {
            label9.Text = "De opgegeven naam bestaat al";
        }
        else {
            pass = client.CreatePass(name); // does work
            client.RegisterCustomer(name,pass);    // does not work           

            Customer c = client.GetCustomer(name); // does not work
            label9.Text = "welkom: " + c.UserName + "\njouw pass: " +c.Password;
        } }

这行代码应该返回Customer的对象......但它没有。

Customer c = client.GetCustomer(name); // does not work

1 个答案:

答案 0 :(得分:0)

解决方案:

InstanceContextMode确实是问题所在:

[ServiceBehavior(InstanceContextMode= InstanceContextMode.Single)]

这是错的:

 public class MyService : IMyService{
    Store store = new Store();

    //your methods here

}

这是对的:

[ServiceBehavior(InstanceContextMode= InstanceContextMode.Single)]
    Store store = new Store();

    //your methods here

}

+1到Marco