Aver
Aver

Reputation: 159

Easy WCF program, service method not working in client program

I just started writing a WCF service and have come across a strange problem. I don't know why method from service invoked in client doesn't work properly and new book is not created. listBooks() method id ok because it returns list of books but method addBook doesn't create new book in booksList. But this situation is only when I use use this method from client because the same method invoked in Service constructor creates a book.

Here is the client code:

namespace LibraryClient
{
class Program
{
    static ServiceReference.ServiceClient client;
    static void Main(string[] args)
    {

        client = new ServiceReference.ServiceClient();

        client.addBook(2, "some book", "some author"); //this is not working
        ServiceReference.Book[] books = client.listBooks();

        foreach(var book in books)
        {
            Console.WriteLine("{0}", book.title);
        }

        Console.ReadLine();

    }
}
}

and service code:

namespace LibraryService
{

public class Service : IService
{

    private static List<Book> booksList;
    private static List<User> usersList;



    public Service()
    {
        booksList = new List<Book>();
        usersList = new List<User>();
        addBook(1, "ANOTHER BOOK", "ANOTHER AUTHOR"); //this is working


    }

    public List<Book> listBooks()
    {

        return booksList;
    }

    public List<User> listUsers() { 
        return usersList;
    }

    public void addBook(int id, string title, string author)
    {
        booksList.Add(new Book(id,title,author));

    }

    }
}

Upvotes: 1

Views: 302

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038800

On the server side, each time you call the service a new instance of the service class will be created. And creating a new instance means that the constructor of this class will be called.

And just look what you are doing in the constructor:

booksList = new List<Book>();
usersList = new List<User>();

Basically you are killing everything that might have been stored in those static lists from previous calls. So make sure that you are instantiating those lists only once to ensure that the information stored in them will persist between multiple calls:

private static readonly List<Book> booksList = new List<Book>();
private static readonly List<User> usersList = new List<User>();

public Service()
{
}

Also bear in mind that the List<T> class is not thread safe. This means that if you have multiple concurrent client calls to your webservice, the data could be corrupted in this list. You might need to synchronize the access to them to prevent this:

private static readonly object syncRoot = new object();

public void addBook(int id, string title, string author)
{
    lock (syncRoot)
    {
        booksList.Add(new Book(id, title, author));
    }
}

Upvotes: 4

Related Questions