Search code examples
.netwcfwcf-client

Should the WCF service stay opened all the time?


I am creating a wcf service, my wcf service now is hosted in a console application as shown below

 PersonService = new ServiceHost(typeof(PersonService));
 PersonService.AddServiceEndpoint(typeof(IPersonService), binding, "http://localhost:5645/PersonService");
 PersonService.Open();

Then I am consuming the wcf service using the ChannelFactory class;

EndpointAddress endPoint = new EndpointAddress("http://localhost:5645/PersonService");
ChannelFactory<IPersonService> engineFactory = new ChannelFactory<IPersonService>(binding, endPoint);
IPersonService personChannel = engineFactory.CreateChannel();

Then i can use this channel to call a method such as

personChannel.GetPersonById("1");
personChannel.Close();

My Question is:

As shown in the code above, the service is always opened while the channel is closed after finishing work with it. Is this a good behavior to keep the service opened, or i should open the service and then close it on each call taking into consideration that i might have two clients calling the same service at the same time.

Please advise.


Solution

  • Well, your service must be kept "open" -- that's your lingo, but in reality the "Open" call puts a listener on the port. The server must keep listening in order to know when a client wants to connect to it. Without this, the client won't be talking to a servier that is not listening.

    When you client is finished and got what it wants, then it can terminate (close) the connection and go away, saving resources on both sides.

    This is like making a phone call. Somebody has to sit next to the phone to "listen" for it to ring. A client picks up a phone and call the service hotline. The service hotline phone rings. That person (who is "listening") picks up the phone and a "connection" (i.e. conversation) starts.

    When the client is finished, he/she drops the phone and the connection is over. However, the person manning the service hotline must continue to "listen" for new rings.