0

我有两个 WinForms 应用程序:一个“服务器”和一个“客户端”。在服务器上

private ServiceHost host;
private const string serviceEnd = "Done";

public Form1()
{
    InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
    List<string> sqlList = new List<string>();
    foreach (string line in this.richTextBoxSql.Lines)
        sqlList.Add(line);
    SqlInfo sqlInfo = new SqlInfo(sqlList);

    host = new ServiceHost(
        typeof(SqlInfo),
        new Uri[] { new Uri("net.pipe://localhost") });

    host.AddServiceEndpoint(typeof(ISqlListing),
            new NetNamedPipeBinding(),
            serviceEnd);

    host.Open();
}

在哪里

public class SqlInfo : ISqlListing
{
    public SqlInfo() {}

    private List<string> sqlList;
    public SqlInfo(List<string> sqlList) : this() 
    {
        this.sqlList = sqlList;
    }

    public List<string> PullSql()
    {
        return sqlList;
    }
}

[ServiceContract]
public interface ISqlListing
{
    [OperationContract]
    List<string> PullSql();
}

在我有的客户端上

private ISqlListing pipeProxy { get; set; }
private const string serviceEnd = "Done";

public Form1()
{
    InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
    List<string> l = pipeProxy.PullSql();
    string s = String.Empty;
    foreach (string str in l)
        s += str + " ";
    this.richTextBoxSql.AppendText(s.ToString());
}

private void Form1_Load(object sender, EventArgs e)
{
    ChannelFactory<ISqlListing> pipeFactory =
    new ChannelFactory<ISqlListing>(
      new NetNamedPipeBinding(),
      new EndpointAddress(
         String.Format("net.pipe://localhost/{0}", serviceEnd)));

    pipeProxy = pipeFactory.CreateChannel();
}

问题是,当我List<string>使用它从服务器“拉”时,pipeProxy.PullSql()它正在调用public SqlInfo() {}默认构造函数并设置sqlList = null.

如何获取此代码以返回RichTextBox服务器应用程序中的文本?

4

1 回答 1

2

这是因为您使用的是这种服务主机:

 host = new ServiceHost(
        typeof(SqlInfo),
        new Uri[] { new Uri("net.pipe://localhost") });

您正在传递一个类型,WCF 框架猜测它必须创建一个类型的实例SqlInfo来处理请求。尝试传递对您构造的SqlInfo实例的引用,即sqlInfo在您的情况下。 使用 ServiceHost 的这个重载,它允许你直接传递实例:

host = new ServiceHost(
            sqlInfo,
            new Uri[] { new Uri("net.pipe://localhost") });
于 2012-12-07T17:33:43.343 回答