I am still struggling with the server part of my wcf application. The following code shows an example WCF Service. Method Getnews
creates an instance of class TOInews
and changes some of its values. The following code works without errors.
namespace WCF_NewsService
{
public class News_Service : INews_Service
{
public TOInews Getnews()
{
TOInews objtoinews = new TOInews();
objtoinews.ID = 1;
objtoinews.Header = "Mumbai News";
objtoinews.Body = "2013 Code contest quiz orgnize by TOI";
return objtoinews;
}
}
}
The following code, in contrast, does not work. And I am wondering why. Now, I want to store the object objtoinews
within my service. I do not want to create a new object each time I access Getnews()
. Therefore, I create a method named Initnews()
, which is only called once (at the beginning) by the client (consumer).
namespace WCF_NewsService
{
public class News_Service : INews_Service
{
TOInews objtoinews;
public TOInews Initnews()
{
objtoinews = new TOInews();
return objtoinews;
}
public TOInews Getnews()
{
objtoinews.ID = 1;
objtoinews.Header = "Mumbai News";
objtoinews.Body = "2013 Code contest quiz orgnize by TOI";
return objtoinews;
}
}
}
When I run this code, I get a System.NullReferenceException
, because, for some reason, objtoinews
equals null
. Can anyone tell me why?
EDIT: Here's how I call it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WCF_NewsConsumer.Proxy_TOInews;
namespace WCF_NewsConsumer
{
class Program
{
static void Main(string[] args)
{
Proxy_TOInews.News_ServiceClient proxy = new News_ServiceClient("BasicHttpBinding_INews_Service");
TOInews Tnews = new TOInews();
Tnews = proxy.Initnews();
Tnews = proxy.Getnews();
Console.WriteLine(" News from:" + Tnews.ID + "\r\r \n " + Tnews.Header + "\r\r \n " + Tnews.Body + "");
Console.ReadLine();
}
}
}