Search code examples
.netwcf

List .Add is not propagated to list variable


I create a list to store some token objects

public class PSService : IPSService
{
    private List<Token> validTokens = new List<Token>();

Then I call a method through SoapUI to add a token to that list.

private bool RegisterToken(Token token)
    {
        validTokens.Add(token);

        //this loop successfully prints the list contents.
        foreach (Token validToken in validTokens)
        {
            Console.WriteLine("registeredToken: " + validToken);
        }
            return true;
    }

(unrelated code removed for clarity)

Then I have another method which reads the content of that list. But when i call it trough SoapUI (after the register call) I do not get the expected response

public bool PostProduct(Token auth, Product item)
        {
            Console.WriteLine("input: " + auth);
            //Console.WriteLine("validtoks: "+ validTokens.First()); 
            foreach (Token tok in validTokens)
            {
                Console.WriteLine("Valid: " + tok);
                Console.WriteLine("Deze zijn equal: " + tok.Equals(auth));
            }

            return false;
        }

(again removed unrelated code)

the (commented) validTokens.First() gives a "List does not contain elements" error. The loop does not execute (since there are no elements)

Methods are all in the same class.

I think I am creating a copy of validTokens within the RegisterToken context, but how do I avoid that?


Solution

  • Due to @Guru stron 's comment i looked into the multiple instances posibility.

    public class PSService : IPSService
    {
        private static List<Token> validTokens = new List<Token>();
    

    making a variable static persists it across all instances of a service. it now works correctly.