Reputation: 27633
I'm creating a WCF ServiceHost
with port 0 in order to get a dynamically assigned port:
ServiceHost host = new ServiceHost(typeof(MyClass), new Uri("net.tcp://localhost:0/abc"));
host.AddServiceEndpoint(typeof(MyInterface), new NetTcpBinding(SecurityMode.None), "net.tcp://localhost:0/abc");
How do I get the port number assigned?
I tried:
host.ChannelDispatchers[0].Listener.Uri.Port
but it just returns 0 which is presumably wrong.
Upvotes: 1
Views: 1913
Reputation: 2563
Alright, I think I figured it out. You need to make sure the listen URI behavior is set to unique and also open it. By default it is set to explicit.
I made a bogus service class that contained the following service contract:
[ServiceContract]
public class MyClass
{
[OperationContract]
public string Test()
{
return "test";
}
}
And added the corresponding test class:
[TestClass]
public class TestMyClass
{
[TestMethod]
public string TestPortIsNotZero(){
var host = new ServiceHost(typeof(MyClass),
new Uri("net.tcp://localhost:0/abc"));
var endpoint = host.AddServiceEndpoint(typeof(MyClass),
new NetTcpBinding(SecurityMode.None), "net.tcp://localhost:0/abc");
//had to set the listen uri behavior to unique
endpoint.ListenUriMode = ListenUriMode.Unique;
//in addition open the host
host.Open();
foreach (var cd in host.ChannelDispatchers)
{
//prints out the port number in the dynamic range
Debug.WriteLine(cd.Listener.Uri.Port);
Assert.IsTrue(cd.Listener.Uri.Port >= 0);
}
}
}
Upvotes: 5