我在控制台应用程序上托管了一个WCF服务,代码是:
public interface ITestService
{
[OperationContract]
void SetField(string data);
[OperationContract]
string GetField();
}
public class TestService : ITestService
{
private string myData;
public string GetField()
{
retrun myData;
}
public void SetField(string data)
{
myData = data;
}
}
然后我将它托管在控制台应用程序上:
ServiceHost host = new ServiceHost(typeof(TestService));
host.Open();
Console.WriteLine("Test Service Host");
Console.WriteLine("Service Started!");
foreach (Uri address in host.BaseAddresses)
{
Console.WriteLine("Listening on " + address);
}
Console.WriteLine("Press any key to close the host...");
Console.ReadLine();
host.Close();
我启动了控制台主机,然后在另一个控制台应用程序中,我引用了该服务并使用它:
TestService client = new TestService();
client.SetField("test");
Console.WriteLine( client.GetField() );
这个打印没有任何意味着该字段仍为空
这项服务有什么问题?
答案 0 :(得分:3)
错误的是,您希望状态会在来电之间保持不变 - 它是 NOT 。默认情况下,WCF绝对是无状态(它们应该是!这是好事!)
如果您需要保留信息 - 将其存储到持久性存储中(例如数据库)。
每个WCF调用(默认情况下)都会获得TestService
全新的,新创建的实例。
因此,您的第二个调用实例知道没有关于第一个实例(由SetField
使用),因此无法返回您在第一个调用中设置的值。
答案 1 :(得分:1)
您应该使用以下属性标记您的服务类:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class TestService : ITestService
{
//...
}
这意味着您的服务必须只有一个实例。你必须像这样创建主机:
var host = new ServiceHost(new TestService()); // or get a singleton..
host.Open();
请注意您使用实例创建服务而不是键入。然后你的代码应该工作。
答案 2 :(得分:0)
试试这个:
将字符串用作静态。
public interface ITestService
{
[OperationContract]
void SetField(string data);
[OperationContract]
string GetField();
}
public class TestService : ITestService
{
private static string myData;
public string GetField()
{
retrun myData;
}
public void SetField(string data)
{
myData = data;
}
}