Figure 20-30
In the code-behind of Form1
, import the following namespace:
using System.ServiceModel;
Declare the following objects:
public partial class Form1 : Form {
The ServiceHost
class is used to host a WCF service. In the Form1_Load
event handler, code the following:
private void Form1_Load(object sender, EventArgs e) {
}
In the design view of Form1
, create an event handler for the FormClosing
event of Form1
by using the Properties window (see Figure 20-31).

Figure 20-31
Code the Form1_FormClosing
event handler as follows:
private void Form1_FormClosing(
object sender, FormClosingEventArgs e) {
}
This code simply ends the hosting of the WCF service when the window is closed.
Define the DisplayMessage()
function within the Form1
class as follows:
//---display a message on the TextBox control---
internal void DisplayMessage(string msg) {
textBox1.Text += msg + Environment.NewLine;
}
In the IMessageService.cs
file, define the operation contract SetMessage
, highlighted here:
namespace MessageServer {
[ServiceContract]
public interface IMessageService {
[OperationContract]
void DoWork();
}
}
The SetMessage()
operation uses the one-way messaging pattern because clients simply send messages to the sender and do not need to wait for a response from the server.
This operation allows clients to send a message to the WCF service.
In the MessageService.cs
file, add the following highlighted code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace MessageServer {
public class MessageService : IMessageService {
public void DoWork() {}
}
}
Notice that the MessageService
class is prefixed with the [ServiceBehavior]
attribute. It contains the InstanceContextMode
property, which is set to Single
.
When a WCF Service receives a message, the message is dispatched to an object's instance methods:
□ A single instance of the receiver may be created for
□ A single instance of the receiver may be created for
The InstanceContextMode
property specifies the number of service instances available for handling calls that are contained in incoming messages. It can be one of the following:
□ Single
— Every received message is dispatched to the same object (a singleton).
□ Percall
— Every received message is dispatched to a newly created object. This is the default.
□ PerSession
— Messages received within a session (usually a single sender) are dispatched to the same object.
□ Shareable
— Messages received within a session (can be one or more senders) are dispatched to the same object.
Edit the App.config
file, using the WCF Service Configuration Editor (you can also select it from Tools→WCF Service Configuration Editor).
Set the following details for the first endpoint (see Figure 20-32).