Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you do NetTcpBinding in code? Should you?

WCF newbie here... I'm trying to self-host a WCF service using NetTcpBinding. Based on the MSDN "how-to" tutorial I have done all the binding in code, which I then changed from WsHttpBinding to NetTcpBinding, and now looks like this:

var baseAddress = new Uri("net.tcp://localhost:8000/MyWebService");
var selfHost = new ServiceHost(typeof(ConcreteWebService), baseAddress);
try {
  var binding = new NetTcpBinding();
  binding.Security.Mode = SecurityMode.Message;
  selfHost.AddServiceEndpoint(typeof(IWebService), binding, "TRWebService");
  selfHost.Open();
  Console.WriteLine("The service is ready at {0}", baseAddress.AbsoluteUri);
  Console.WriteLine("Press <ENTER> to terminate service.");
  Console.WriteLine();
  Console.ReadLine();

  selfHost.Close();
} catch (CommunicationException ce) {
  Console.WriteLine("An exception occurred: {0}", ce.Message);
  selfHost.Abort();
}

Thing is, the tutorial then says you have to run svcutil.exe to generate a proxy for the client... but since I switched to NetTcpBinding, svcutil doesn't work anymore - can't detect my service. I googled the issue, and found that every single example out there of NetTcpBinding does the setup in the app.config file, not in code, and they all add an endpoint called "Mex", with binding type of "mexTcpBinding". There doesn't appear to be any equivalent of this in code.

So, do I have to change my project to use app.config, and abandon the code-based approach? Can anyone explain to me what Mex is, why I need it, and why it (apparently) can't be called in code - or if it can, how, or why is it discouraged? In general, when is it better to use app.config, and when code for WCF services?

like image 341
Shaul Behr Avatar asked Dec 26 '10 16:12

Shaul Behr


1 Answers

If you use netTcpBinding - and in a "behind-the-corporate-firewall" LAN environment, it's definitely a great idea to do so - you need to also expose a MEX endpoint (Metadata Exchange) using the mexTcpBinding in order for svcutil to be able to detect and find that service.

MEX = Metadata Exchange is the mechanism that WCF uses to "publicly advertise" what a service looks like. If you have a MEX endpoint, then utilities like svcutil can query and "discover" a service, e.g. find out about all the service methods it exposes, about the parameters it expects to get and so on.

To add a MEX endpoint, you can definitely use code, too! Something like this fragment:

var mexBinding = MetadataExchangeBindings.CreateMexTcpBinding();
selfHost.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, "mex");

Without MEX, you need to somehow "tell" the client trying to consume your service what it is your service offers so that the client can make sure to call the proper methods with the proper parameters.

like image 59
marc_s Avatar answered Sep 19 '22 13:09

marc_s