开发者

Web service class field is null after the web method is executed?

开发者 https://www.devze.com 2023-02-03 18:49 出处:网络
I have a Web Service project and a WPF project (which serves as a client) in my solution. The class representing the web service is quite simple and looks like this:

I have a Web Service project and a WPF project (which serves as a client) in my solution.

The class representing the web service is quite simple and looks like this:

public class CardsGameService : System.Web.Services.WebService
{
    private Card magicCard;

    // Acts as a getter for magicCard field
    [WebMethod]
    public Card GetMagicCard()
    {
        return magicCard;
    }

    // Creates some random cards and sets the magicCard field
    [WebMethod]
    public Card[] GetNewCardSet()
    {
        Card[] cardSet = new Card[4];

        for (int i = 0; i < 4; i++)
        {
            cardSet[i] = GetRandomCard();
        }

        Random random = new Random();
        int index = random.Next(0, 3);

        // This field does get its value and 
        // is not null when this method is executed
        magicCard = cardSet[index];

        return cardSet;
    }
}

In my client WPF code-behind class, I am instantiating CardsGameServiceSoapClient service and calling the GetNewCardSet() web method which returns the set of cards.

Here's the problem:

If I want to call the web method GetMagicCard() later on, it always returns null. Why? I am instantiating CardsGameServiceSoapClient service only once and this object is alive for as lo开发者_StackOverflow中文版ng as I run my client application.


Because the WebService instance is created and discarded on a per-call basis. If you want to share state between multiple web service calls, then use a static field. But beware that you need to worry about the same kind of issues you would when dealing with any other multi-threaded code. Two calls could be in progress at the same time so you need to use locks where appropriate.

Also worth mentioning is that IIS can and will terminate your application domain for any reason at any time so you shouldn't rely on the fact that the field will hang around indefinitely. If you need it to persist then use a database or other persistent storage.


The problem is that, while your proxy client object (CardsGameServiceSoapClient) is alive between the two calls, each call to your service is a brand new request and the server object is instantiated on each request.... you would need to create and initialize your object for each web method (perhaps init it in a constructor?)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号