簡體   English   中英

如何在WCF服務內的多個調用之間保留對象狀態? 獲取“ System.NullReferenceException”

[英]How to retain object state across multiple calls within a WCF Service? Getting a “System.NullReferenceException”

我仍然在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();
        }
    }
}

只是為了澄清我的意見-您需要在合同上使用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會話,因為它們限制了解決方案的可擴展性(因為服務器每個會話消耗線程和資源),並且還需要粘性會話路由,因為必須將會話路由回到同一服務器中。多服務器方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM