S. Butts
S. Butts

Reputation: 89

Member variables of an ASMX Web service always reinitialized

I am creating a C# Web service in VS 2010 to pass data from another software program to the service consumer. For reasons too complicated to go into here, the Web service I am writing is supposed to keep track of some information for the life of the session. This data is tied to the other software program. I have put the information in the WebService class as member variables. I have created objects of the Webservice class in another program, and kept these objects around. Unfortunately, the data in the Webservice object does not last beyond the scope of the current function. Here is what I have:

/* the Web service class */
public class Service1 : System.Web.Services.WebService
{
    protected string _softwareID;
    protected ArrayList _softwareList;

    public Service1()
    {
        _softwareID= "";
        _softwareList = new ArrayList();
    }

    [WebMethod]
    public int WebServiceCall(int request)
    {
        _softwareID = request;
        _softwareList.Add(request.ToString());
        return 1;
    }

    /* other Web methods */
}

/* the form in the application that will call the Web service */
public partial class MainForm : Form
{
    /* the service object */
    protected Service1 _service;

    public MainForm()
    {
        InitializeComponent();
        _service = null;
    }

    private void startSoftware_Click(object sender, EventArgs e)
    {
        //initializing the service object
        _service = new Service1();
        int results = _service.WebServiceCall(15);
        /* etc., etc. */
    }

    private void doSomethingElse_Click(object sender, EventArgs e)
    {
        if (_service == null)
        {
            /* blah, blah, blah */
            return;
        }
        //The value of service is not null
        //However, the value of _softwareID will be a blank string
        //and _softwareList will be an empty list
        //It is as if the _service object is being re-initialized
        bool retVal = _service.DoSomethingDifferent();
    }
}

What can I do to fix this or do differently to work around it? Thanks in advance to anyone who helps. I am brand-spankin' new at creating Web services.

Upvotes: 2

Views: 1652

Answers (1)

Guvante
Guvante

Reputation: 19223

Assuming you are calling a WebService, Service1 will be initialized using the default constructor during every call. This is part of the design.

If you need to persist data between method calls, you will need to persist it in some way other than updating the class.

There are several ways to do it, and which is best depends on your needs:

  • Database, probably the safest and gives permanent persistance
  • Static dictionary with a key passed to each call, or using the IP address as the key
  • HTTP Session object (I am unsure how this interacts with WebServices)

Upvotes: 2

Related Questions