WCF tips & tricks

Let’s start

WCF has superseded the old asmx, but the underlying layer for communications is always an operating system’s module: in particular, if you choose a service host, you are going to miss some iis functionalities that make your deploy easier.


Service Host

Though, service host is an important way to expose the WCF service and could be the only feasible solution for some environments.


Open Service

In that case, remember to monitor the events involving relevant exception management.

protected override void OnStart(string[] args)
	if (serviceHost != null) {
	serviceHost = new ServiceHost(typeof(CentralReport.AllocService));
	serviceHost.Opening += new EventHandler(serviceHost_Opening);
	serviceHost.Opened += new EventHandler(serviceHost_Opened);
    serviceHost.Closing += new EventHandler(serviceHost_Closing);
    serviceHost.Closed += new EventHandler(serviceHost_Closed);
    serviceHost.Faulted += new EventHandler(serviceHost_Faulted);
    serviceHost.UnknownMessageReceived += new EventHandler<UnknownMessageReceivedEventArgs>(serviceHost_UnknownMessageReceived);
    CentralReport.AllocService.SrvLog("WinCentralRpt","Windows service started");


Call mechanism

You will be surprised to discover that any call to your service contractual operations will cause the instantiation of your service implementation, thus the constructor will be invoked! Learn this new lesson and implement ctor logging. A generic useful utility follows.


public static void SrvLog(string user, string line) {
	string log_path = System.Configuration.ConfigurationManager.AppSettings["service_log"];
	if (log_path != null) {
		using (System.IO.StreamWriter logSW = new System.IO.StreamWriter(
			log_path.Replace("{user}",user.ToLower()),true)) {
			logSW.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt", CultureInfo.InvariantCulture) + ": " + line);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s