views:

94

answers:

3

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)?

A: 

This seems fine to me if you are OK with the limitations of a fixed binding and server address .

You must be sure that the code within the using lasts as long as you want the host to be available.

Timores
+3  A: 

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:

if (_Host.State == CommunicationState.Faulted)
{
    _Host.Abort();
}
else
{
    _Host.Close();
}
Stefan Egli
Yea, I have heard about this issue. So it applies to this case, I see.
mafutrct
yes, I had to find out the hard way that this problem does not only apply to the clients but to the hosts as well...
Stefan Egli
A: 

If I would implement that Self Host, I would put it in a Windows Service, using the events OnStart and OnStop. Also, do the following changes for best practices:

  • Put the endpoint config in a App.Config file - better to manage in a production enviroment.
  • Separate the Host Service from the implementation and contract binaries.

You can also look at MSDN: http://msdn.microsoft.com/en-us/library/ms730158%28v=VS.90%29.aspx There's a good how to "Host the service in a Windows Service"

Erup
I believe putting the host for _testing_ in a Windows Service is overkill or unpractical at least.
mafutrct
I dont think so. If you search in MSDN, the best practices to implement Self Host, is installing it using Windows Services. Anyway, its better to deploy using the type of hosting you tested before.
Erup