Wednesday, September 21, 2016

Initialize a net.tcp based WCF service in IIS

Last week I helped a colleague who couldn’t understand why the initialization logic of his WCF service wasn’t invoked. He created a WCF service that he wanted to host in IIS and had put the initialization logic inside the Application_Start method inside the global.asax. The Application_Start method is called when the application is started as part of the ASP.NET pipeline. To be more precisely, it is called when the HttpApplication type is instantiated. This happens when the first HTTP arrives into the application.

However the WCF service wasn’t using HTTP binding but used the net.tcp binding instead(which works perfectly fine in IIS). This also meant that the Application_Start method is never invoked as no HTTP call will ever arrive.

Fortunately, ASP.NET provides a simple hook that works in a protocol agnostic way. The hook is based on the following method:

public static void AppInitialize();

This method can be put in any class that is defined in a C# file in the application’s \App_Code directory. When the AppDomain is started, this method is invoked.

Note: The file must be added to the project as a code file and NOT as part of an assembly.

No comments: