Is this the right way to host a WCF service?

For some testing code, I would like to be able to host the WCF service in just a few lines. I decided that I would 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 (); } } 

This can be used as follows:

 using (var host = new WcfHost<ImplementationClass, ContractClass> ()) { 

Is there something wrong with this approach? Is there a flaw in the code (especially about recycling)?

+4
source share
3 answers

The host's Dispose method may throw an exception if the host is in a failed state. If this happens, you will not see what actually went wrong, as the original exception is lost. For test code, this may not be a problem, but it may still be in your way if you try to understand why something is not working.

I have not tested it, but in your Dispose method should be fine:

 if (_Host.State == CommunicationState.Faulted) { _Host.Abort(); } else { _Host.Close(); } 
+5
source

It seems fine to me if everything is fine with the limitations of a fixed binding and server address.

You need to be sure that the code in using lasts as long as you want the host to be accessible.

0
source

If I implemented this Self Host, I would put it in a Windows service using the OnStart and OnStop events. In addition, make the following changes to best practices:

  • Put the endpoint configuration in the App.Config file - better managed in a production environment.
  • 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 is good, like "Install service in Windows service"

0
source

Source: https://habr.com/ru/post/1306667/


All Articles