在以前的WCF中,Client调用一个Service,首先得知道Service的Address.
当客户端不能确定这个Address的时候呢?一个不恰当的比方:当您不知道某人的住所却又想找到他的时候?
WCF4.0发布的Discovery 功能 或许可以满足这个需要.
WCF4.0-Discovery 提供了 Ad-Hoc & Managed 模式。
具体信息:
http://msdn.microsoft.com/en-us/library/dd456791.aspx
这里仅仅是一个小小的Demo,方便自己查找Code而已^_^.
运行效果:(运行的2个Service端)
2个Console程序.
1. Service端
Program.cs
Program.csnamespace WCFDiscoveryServer
{
class Program
{
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://localhost:8000/" + Guid.NewGuid().ToString());
using (ServiceHost serviceHost = new ServiceHost(typeof(LoginService), baseAddress))
{
serviceHost.AddServiceEndpoint(typeof(ILogin), new WSHttpBinding(), String.Empty);
// Discoverable @ UDP multicast
serviceHost.Description.Behaviors.Add(new ServiceDiscoveryBehavior());
serviceHost.AddServiceEndpoint(new UdpDiscoveryEndpoint());
serviceHost.Open();
Console.WriteLine("Service started at {0}", baseAddress);
Console.WriteLine();
Console.WriteLine("Press any key to terminate the service.");
Console.WriteLine();
Console.ReadKey();
}
}
}
}
ILogin.cs
ILogin.csnamespace WCFDiscoveryServer
{
[ServiceContract]
public interface ILogin
{
[OperationContract]
string Echo(string input);
}
}
LoginService.cs
LoginService .csnamespace WCFDiscoveryServer
{
public class LoginService : ILogin
{
public string Echo(string input)
{
string result = string.Format("You said:{0} @{1}", input, DateTime.Now);
Console.WriteLine(result);
return result;
}
}
}
2.Client端
ILogin.cs
ILogin .csnamespace WCFDiscoveryClient
{
[ServiceContract]
public interface ILogin
{
[OperationContract]
string Echo(string input);
}
}
Program.cs
Program.csnamespace WCFDiscoveryClient
{
class Program
{
static void Main(string[] args)
{
DiscoveryClient discoveryClient = new DiscoveryClient(new UdpDiscoveryEndpoint());
Console.WriteLine("Finding ILogin endpoints...");
Console.WriteLine();
// Find ILogin service endpoints
FindResponse findResponse = discoveryClient.Find(new FindCriteria(typeof(ILogin)));
Console.WriteLine("Found {0} ILogin endpoint.", findResponse.Endpoints.Count);
Console.WriteLine();
EndpointAddress address;
if (findResponse.Endpoints.Count > 0)
{
address = findResponse.Endpoints[0].Address;
foreach (var item in findResponse.Endpoints)
{
Console.WriteLine(item.Address.Uri.ToString());
}
ILogin loginService = ChannelFactory<ILogin>.CreateChannel(new WSHttpBinding(), findResponse.Endpoints[0].Address);
Console.WriteLine(loginService.Echo("Test"));
}
Console.WriteLine("Press any key to exit.");
Console.WriteLine();
Console.ReadKey();
}
}
}