JEtheDBA JEtheDBA - 15 days ago 6
C# Question

C# Cannot add or modify List in WCF

I am using example code from a tutorial on Creating a WCF Service and it only half works. Adding to the List works when it's hard-coded and retrieving the List works. However, using a routine to Add or modify the List does not work. Here is the code:
BookData.cs

using System.Runtime.Serialization;

namespace BookServicesV2
{
[DataContract]

public class BookData
{
[DataMember]
public int BookID { get; set; }
[DataMember]
public string Title { get; set; }
[DataMember]
public string Author { get; set; }
[DataMember]
public decimal Price { get; set; }
}
}


BookService.cs:

using System.Collections.Generic;


namespace BookServicesV2
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together.
public class BookService : IBookService
{
private List<BookData> _books;

private BookService()
{
_books = new List<BookData>();

var book = new BookData { BookID = 1, Author = "Shakespeare", Title = "To Be or Not To Be", Price = 1.49M };
_books.Add(book);

book = new BookData { BookID = 2, Author = "Mark Twain", Title = "Not Dead Yet", Price = 3.50M };
_books.Add(book);
}

#region IBookService Members

public void AddBook(BookData book)
{
if (book != null) _books.Add(book);
}

public void UpdatePrices(decimal increaseAmmount)
{
foreach (var book in _books)
{
book.Price += increaseAmmount;
}
}

public List<BookData> GetBooks()
{
return _books;
}

#endregion
}
}


When I launch the WCF Test Client, GetBooks retrieves the two hard-coded books. When I use AddBook or UpdatePrices and then GetBooks, nothing has changed. I'm basically learning c# and WCF on the fly, so I am completely stumped. Thanks!

Answer

Try changing the service behavior of your BookService.cs.

 [ServiceBehavior(  ConcurrencyMode = ConcurrencyMode.Multiple, 
                   InstanceContextMode = InstanceContextMode.Single )]
public class BookService : IBookService{...}

This will change it to a singleton object. In other words, only 1 instance of your service is created.

You can also use InstanceContextMode = InstanceContextMode.PerSession as well. That means an object is created and maintained for each connection. If you close the connection and then re-connect you would have a new instance but you would be dealing with the same instance for each subsequent call you made to the service (assuming you don't close/reconnect).