首页 文章

WCF中的动态通道工厂

提问于
浏览
3

我在我的WCF服务中使用以下代码来调用另一个可能是也可能不是WCF服务的Web服务 .

ChannelFactory<IService1> myChannelFactory = new ChannelFactory<IService1>
                                                  (myBinding, myEndpoint);

所以我希望在xml文件中有一些信息,我从中读取各种服务 endpoints ,并希望将绑定信息传递给通道工厂,并根据配置XML文件中的信息调用其他服务 .

所以我想每次使用不同的服务 Contract 信息动态生成通道工厂 .

是否可以在渠道工厂中使用各种服务具有不同的接口?

换句话说,从上面的代码我有 IService1 但是当我从xml文件中读取另一个服务信息时,我想用另一个接口创建一个通道?

1 回答

  • 6

    是的,可以通过 Generics:

    public static T CreateProxyChannel<T>()
    {
        string endpointUri = GetServiceEndpoint(typeof(T));
    
        ChannelFactory<T> factory = new ChannelFactory<T>(myBinding, new EndpointAddress(new Uri(endpointUri)));
    
        return factory.CreateChannel();
    }
    

    并且 GetServiceEndpoint 方法根据T的类型返回 endpoints :

    private static string GetServiceEndpoint(Type service)
    {
        string serviceTypeName = service.Name;
    
        // Code to get and return the endpoint for this service type
    }
    

    请注意,在这种情况下,我希望配置文件具有与服务类型名称关联的 endpoints (例如 IService1http://localhost/Service1.svc ) .

    最后使用它:

    IService1 serviceProxy1 = CreateProxyChannel<IService1>();
    serviceProxy1.MyMethod();
    
    IService2 serviceProxy2 = CreateProxyChannel<IService2>();
    serviceProxy2.AnotherMethod();
    

相关问题