我想通过单例从表单中获取一些数据并通过WCF发送它:
WCF图书馆:
namespace ServerWcf
{
public class MyWcf : IMyWcf
{
public int GetData()
{
return Singleton.form.GetSomeData();
}
}
[ServiceContract]
public interface IMyWcf
{
[OperationContract]
int GetData();
}
}
的Singleton:
public interface IGenerator
{
int GetSomeData();
}
public class Singleton
{
public static readonly Singleton Instance = new Singleton();
public void Add(IGenerator generator)
{
form = generator;
}
public static IGenerator form;
}
并形成:
public partial class Form1 : Form, IGenerator
{
//some fields and methods
private void Form1_Load(object sender, EventArgs e)
{
Singleton.Instance.Add(this);
}
public int GetSomeData()
{
return SomeDataFromForm;
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = Convert.ToString(Singleton.form.GetData());
}
}
所以,当我试图从另一个应用程序(甚至是同一个)调用GetData()
WCF函数时,我得到了这个:
FaultException'1 is unhandled
object reference not set to an instance of an object
通过搜索互联网我发现只响应:“这是你的服务器代码中的一个错误,继续调试”。但与此同时button1_Click完美无缺!
所以,问题是:怎么可能呢?我的猜测是WCF库正在尝试创建Singleton
类的新实例。我对吗?如果是这样 - 我该如何解决?
P.S。 WCF连接也有效:如果我将GetData()
更改为
public int GetData()
{
return 1;
}
效果很好。
错误的确切位置在自动生成的文件Reference.cs中。它看起来像这样:
public partial class MyWcfClient : System.ServiceModel.ClientBase<WindowsFormsApplication1.Server.IMyWcf>, WindowsFormsApplication1.Server.IMyWcf {
public MyWcfClient() {
}
public MyWcfClient(string endpointConfigurationName) :
base(endpointConfigurationName) {
}
public MyWcfClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public MyWcfClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public MyWcfClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress) {
}
public int GetData()
{
return base.Channel.GetData(); // <== The error occurs here
}
}
}