ciprianr
ciprianr

Reputation: 309

How can i manage application state when using a wcf service hosted in the application?

I am a beginner with wcf and i have come across this interesting problem that i can't solve.

So i have the following service(simplified obviously).

The contract:

class IService
{
    [OperationContract]
    void setList(string sourceName);

    [OperationContract]
    List<aux> returnList();         
}

[DataContract]
class ServiceData
{   
    //Coresponding data member property = ListOfAuxiliaryData
    [DataMember]
    List<auxData> listOfAuxiliaryData;
}

class auxData
{
    //all these members have corresponding properties using the first capital letter   convention 
    string name;
    List<string> auxiliaryDataInformation;
}

After that i implemented the service like so:

class SerivceImplementation:IContract
{
     ServiceData serviceData = new ServiceData()

     setList(string sourceName)
     {
         //this works
         serviceData.ListOfAuxiliaryData = GetListFromValidDataSource(sourceName);
     }

     List<auxData> getList()
     {
          return serviceData.ListOfAuxiliaryData;
     }

}

All was good. I implemented a service host without a problem so the next logical step was to implement a client. I used wpf as a client and used an observable collection as the proxy collection type. So i started to implement like so

ServiceReference.ServiceClient Proxy = new ServiceClient();    

    public MainWindow()
    {
        InitializeComponent();
        Proxy.setList("Questions.Json");
        var listOfQuestions = Proxy.getListOfQuestions();
    }

My problem is that even though the list is set correctly for some reason (found this after some debugging) when i try to get the list if first executes the first line of the implementation where the service data is initialized and logically it returnes a null resulting in everyone's favorite null pointer exception.

What is happening and how can i solve this problem.

Please help, Ciprian

Upvotes: 0

Views: 192

Answers (1)

nvoigt
nvoigt

Reputation: 77334

If there is no need for a state in your service, you should not hold one:

[OperationContract]
void setList(string sourceName);

[OperationContract]
List<aux> returnList(); 

This could easily be

[OperationContract]
List<aux> getList(string sourceName); 

A service is normally not stateful. You can have various means to actually let it hold a state, but out-of-the-box, whenever you open a new client, a new service gets instantiated on the other end. Nothing is saved in between.

Upvotes: 1

Related Questions