C# 单态WCF
我想通过singleton从表单中获取一些数据,并通过WCF发送: WCF库:C# 单态WCF,c#,wcf,singleton,C#,Wcf,Singleton,我想通过singleton从表单中获取一些数据,并通过WCF发送: WCF库: namespace ServerWcf { public class MyWcf : IMyWcf { public int GetData() { return Singleton.form.GetSomeData(); } } [ServiceContract] public interface IMy
namespace ServerWcf
{
public class MyWcf : IMyWcf
{
public int GetData()
{
return Singleton.form.GetSomeData();
}
}
[ServiceContract]
public interface IMyWcf
{
[OperationContract]
int GetData();
}
}
单身人士:
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
通过搜索互联网,我只找到了这样的回答:“这是服务器代码中的错误,请继续调试”。但同时,按钮1_点击工作完美
那么,问题是:这怎么可能?我猜想WCF库正在尝试创建一个新的单例类实例。我说得对吗?如果是,我如何修复它
另外,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
}
}
}
公共部分类MyWcfClient:System.ServiceModel.ClientBase,WindowsFormsApplication1.Server.IMyWcf{
公共MyWcfClient(){
}
公共MyWcfClient(字符串endpointConfigurationName):
基本(endpointConfigurationName){
}
公共MyWcfClient(字符串endpointConfigurationName,字符串remoteAddress):
基本(endpointConfigurationName,remoteAddress){
}
公共MyWcfClient(字符串endpointConfigurationName,System.ServiceModel.EndpointAddress remoteAddress):
基本(endpointConfigurationName,remoteAddress){
}
公共MyWcfClient(System.ServiceModel.Channel.Binding绑定,System.ServiceModel.EndpointAddress remoteAddress):
基址(绑定、远程地址){
}
公共int GetData()
{
return base.Channel.GetData();//您的空引用异常发生在哪里?您在哪里声明和设置此变量的值SomeDataFromForm
?@scartag简化后,它是此表单中的TextBox值,转换为int。@RobertHarvey将此信息添加到问题中。