For some testing code, I’d like to be able to host a WCF service in only a few lines. I figured I’d write a simple hosting class:
public class WcfHost<Implementation, Contract> : IDisposable
where Implementation : class
where Contract : class
{
public readonly string Address = "net.tcp://localhost:8000/";
private ServiceHost _Host;
public WcfHost ()
{
_Host = new ServiceHost (typeof (Implementation));
var binding = new NetTcpBinding ();
var address = new Uri (Address);
_Host.AddServiceEndpoint (
typeof (Contract),
binding,
address);
_Host.Open ();
}
public void Dispose ()
{
((IDisposable) _Host).Dispose ();
}
}
That can be used like this:
using (var host = new WcfHost<ImplementationClass, ContractClass> ()) {
Is there anything wrong with this approach? Is there a flaw in the code (esp. about the disposing)?
The Dispose method of the host can throw an exception if the host is in “faulted” state. If this happens you will not see what actually went wrong as the original exception is lost. For test code this might not be an issue but it still can be in your way if you try to figure out why something does not work.
I did not test it but the following should be OK in your Dispose method: