Hosting WCF in SharePoint 2007

If your MOSS site has controls or webparts based on Silverlight, you may need a WCF service for server side operations. Hosting this WCF service in Sharepoint web application is obvious choice for most of developers, however, SharePoint 2007 does not allow WCF to be hosted inside a web application.  Therefore we need to create a custom VirtualPathProvider and install that using HttpModule.

The Steps are:

1) Create a directory in the WSS site virtual directory so that relevant security permissions are simply inherited. Run the following – “%windir%\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe” -r –y .This Re-registers the current version of WCF and updates scriptmaps at the IIS metabase root

2) Create a WCF library and install it in GAC.

3) Create the relevant .svc file in the directory created above.put all thwe configurations in the a web.config specific to this folder.

4) Create a Virtual Path Provider and register it using a http Module.

SPVirtualPathProvider isn’t coded to handle URLs that start with ‘~’. So we need to have our own as:

 

public class WCFVirtualPathProvider : VirtualPathProvider
{
  public override string CombineVirtualPaths(string basePath, string relativePath)
  {
    return Previous.CombineVirtualPaths(basePath, relativePath);
  }

  // all other methods omited, they simply call Previous… like the above.
  public override bool FileExists(string virtualPath)
  {
    string fixedVirtualPath = virtualPath;
    if (    virtualPath.StartsWith(“~”) && virtualPath.EndsWith(“.svc”)   )
   {
      fixedVirtualPath = virtualPath.Remove(0, 1);
    }
    return Previous.FileExists(fixedVirtualPath);
  }
  protected override void Initialize()
  {
    base.Initialize();
  }
}

5) Register the provider using a custom httpModule as:

Our HttpModule will run after Sharepoint’s “SPRequest” module. Since SPVirtualProvider is registered by the “SPRequest” module at startup, we know our VirtualPathProvider will always come into play *after* Sharepoint’s SPVirtualPathProvider and therefore, we will get a chance to patch the request’s virtual path before it reaches Sharepoint.

public class WCFVPPRegModule: IHttpModule
  {
  static bool wcfProviderInitialized = false;
  static object locker = new object();
  public void Init(HttpApplication context)
    {
      if (!wcfProviderInitialized)
      {
        lock (locker)
      {
      if (!wcfProviderInitialized)
      {
        WCFVirtualPathProvider wcfVPP = new WCFVirtualPathProvider();
        HostingEnvironment.RegisterVirtualPathProvider(wcfVPP);
        wcfProviderInitialized = true;
      }
    }
   }
  }
#region IHttpModule Members
  public void Dispose()
  {
  }
#endregion
}

Leave a Reply