我仍在努力使用我的wcf应用程序的服务器部分。以下代码显示了示例WCF服务。方法Getnews
创建类TOInews
的实例并更改其某些值。以下代码可以正常运行。
namespace WCF_NewsService
{
public class News_Service : INews_Service
{
public TOInews Getnews()
{
TOInews objtoinews = new TOInews();
objtoinews.ID = 1;
objtoinews.Header = "Mumbai News";
objtoinews.Body = "2013 Code contest quiz orgnize by TOI";
return objtoinews;
}
}
}
相反,以下代码不起作用。我想知道为什么。现在,我想将对象objtoinews
存储在我的服务中。我每次访问Getnews()
时都不想创建新对象。因此,我创建了一个名为Initnews()
的方法,该方法仅由客户端(消费者)调用一次(在开头)。
namespace WCF_NewsService
{
public class News_Service : INews_Service
{
TOInews objtoinews;
public TOInews Initnews()
{
objtoinews = new TOInews();
return objtoinews;
}
public TOInews Getnews()
{
objtoinews.ID = 1;
objtoinews.Header = "Mumbai News";
objtoinews.Body = "2013 Code contest quiz orgnize by TOI";
return objtoinews;
}
}
}
当我运行此代码时,我得到System.NullReferenceException
,因为出于某种原因,objtoinews
等于null
。谁能告诉我为什么?
编辑:以下是我的称呼方式:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WCF_NewsConsumer.Proxy_TOInews;
namespace WCF_NewsConsumer
{
class Program
{
static void Main(string[] args)
{
Proxy_TOInews.News_ServiceClient proxy = new News_ServiceClient("BasicHttpBinding_INews_Service");
TOInews Tnews = new TOInews();
Tnews = proxy.Initnews();
Tnews = proxy.Getnews();
Console.WriteLine(" News from:" + Tnews.ID + "\r\r \n " + Tnews.Header + "\r\r \n " + Tnews.Body + "");
Console.ReadLine();
}
}
}
答案 0 :(得分:1)
只是为了澄清我的评论 - 您需要在合同上使用SessionMode=Required
,以便服务器在多个调用中保留构造对象的状态:
[ServiceContract(SessionMode=SessionMode.Required)]
public interface INews_Service
{
// Initiating - indicates this must be called prior to non initiating calls
[OperationContract(IsInitiating=true, IsTerminating=false)]
TOInews Initnews();
// You can choose whether this terminates the session (e.g. if more calls)
[OperationContract(IsInitiating=false, IsTerminating=true)]
TOInews Getnews();
}
您还需要重新生成客户端以更新绑定和代理。
也就是说,应谨慎使用WCF会话,因为它们会限制解决方案的可扩展性(因为服务器会占用每个会话的线程和资源),并且还需要粘性会话路由,因为会话必须路由回到多服务器场景中的同一台服务器。