WCF SOAP and REST Multi-Project Visual Studio Templates
I’ve been doing quite a bit more WCF work lately and found myself creating the same kind of WCF SOAP projects over and over again. So I dusted off my blog post on building multi-project Visual Studio templates and set off to build a WCF SOAP Multi-Project Template, which I uploaded the Visual Studio Extensions Gallery.
To install the WCF Soap Multi-Project Template, simply open Visual Studio, then select Extensions Manager from the Tools menu. Select the Templates category from the Online Gallery, then search for “WCF SOAP”.
Click Download, then install the template. To use the template, select New Project from the File menu, then click on the WCF category, where you should see the “WCF SOAP Service” template.
It’s a similar idea as the REST Template, but using SOAP services. I placed Entities and Services into separate projects than the Web host, but I split out the service interface into its own project so that it could be shared between the service and client projects – I typically use a channel factory in the client and it needs the interface. In addition there is a Common project with a Namespaces class that has constants that replace magic strings for xml namespaces on the service and data contracts.
The template comes with one other goodie: a ClientChannel class to encapsulate the client proxy and implement IDisposable so that it aborts the communication channel without throwing an exception if it is in a faulted state.
public class ClientChannel<TChannel> : IDisposable
{
private bool _disposed;
public ClientChannel(TChannel channel)
{
Channel = channel;
}
public TChannel Channel { get; private set; }
void IDisposable.Dispose()
{
if (_disposed) return;
Dispose(false);
_disposed = true;
}
protected virtual void Dispose(bool disposing)
{
var channel = Channel as ICommunicationObject;
if (channel != null)
{
try
{
if (channel.State != CommunicationState.Closed)
channel.Close();
}
catch
{
channel.Abort();
}
}
}
}
The TChannel type argument is the service contract interface. Here is how the client uses this class to communicate with the service.
var factory = new ChannelFactory<ISampleService>('soap-basic');
using (var client = new ClientChannel<ISampleService>(factory.CreateChannel()))
{
var item1 = client.Channel.GetItemById(1);
}
The web host exposes a basic http endpoint using the built-in ASP.NET Development Web Server and a fixed port number, which you can easily change. Just remember to change the port number in the client endpoint address found in the client’s app.config file. Enjoy.
Download the code for this post.
Reference: WCF SOAP and REST Multi-Project Visual Studio Templates from our NCG partner Tony Sneed at the Tony Sneed’s Blog blog.