Home Articles

使用WCF发现在客户端上无法发现一个服务中的多个 Contract

Asked
Viewed 737 times
1

我想开发一个WCF服务来支持多个 Contract . 我设法通过遵循Stackoverflow上的post的指令来完成这项工作 .

所以基本上创建一个服务(FooBarService)来实现多个 Contract (IFooService,IBarService) .

string serviceAddress = "net.tcp://localhost:8088/FooBarService";

    ServiceHost selfServiceHost = new ServiceHost(typeof(FooBarService));            

    // The endpoints need to share this binding.
    var binding = new NetTcpBinding();

    selfServiceHost.AddServiceEndpoint(typeof(IFooService), binding, serviceAddress);
    selfServiceHost.AddServiceEndpoint(typeof(IBarService), binding, serviceAddress);

但具有挑战性的是,我还希望使用WCF Discovery发现此服务,以便将客户端和服务与 endpoints 绑定分离 .

在服务方面,我做了类似这样的事情:

var discoveryBehavior = new ServiceDiscoveryBehavior();
    discoveryBehavior.AnnouncementEndpoints.Add(new AnnouncementEndpoint(new NetTcpBinding(SecurityMode.None), new EndpointAddress("net.tcp://localhost:8001/Announcement")));
    _serviceHost.Description.Behaviors.Add(discoveryBehavior);
    _serviceHost.AddServiceEndpoint(new UdpDiscoveryEndpoint());

似乎该服务可以工作 .

但是在一个想要仅使用 Contract IFooService的客户端上,当我尝试发现它时,我总是遇到以下错误 .

无法发现contract.IFooService的 endpoints . 要么没有服务,要么不支持发现 .

您是否认为在这种情况下是否可以在一个服务中实现可发现的多个 Contract ?

如果是,我怎么能根据我现在的代码做到这一点?

谢谢 .

1 Answer

  • 2

    我认为这是可能的 . 首先尝试做最简单的事情,看看是否有效:

    string serviceAddress = "net.tcp://localhost:8088/FooBarService";
    
    ServiceHost selfServiceHost = new ServiceHost(typeof(FooBarService));            
    
    // The endpoints need to share this binding.
    var binding = new NetTcpBinding();
    
    selfServiceHost.AddServiceEndpoint(typeof(IFooService), binding, serviceAddress);
    selfServiceHost.AddServiceEndpoint(typeof(IBarService), binding, serviceAddress);
    
    // Add ServiceDiscoveryBehavior
    selfServiceHost.Description.Behaviors.Add(new ServiceDiscoveryBehavior());
    
    // Add a UdpDiscoveryEndpoint
    selfServiceHost.AddServiceEndpoint(new UdpDiscoveryEndpoint());
    

    客户:

    static EndpointAddress FindCalculatorServiceAddress()
    {
        // Create DiscoveryClient
        DiscoveryClient discoveryClient = new DiscoveryClient(new UdpDiscoveryEndpoint());
    
        // Find ICalculatorService endpoints            
        FindResponse findResponse = discoveryClient.Find(new FindCriteria(typeof(IFooService)));
        if (findResponse.Endpoints.Count > 0)
        {
            return findResponse.Endpoints[0].Address;
        }
        else
        {
            return null;
        }
    }
    

    还要确保您可以使用两个不同的 Contract 创建客户端并手动调用服务 .

Related