简体   繁体   English

WCF中的动态通道工厂

[英]Dynamic Channel Factory in WCF

I am using the following code in my WCF service to call another web service which may or may not be a WCF service. 我在我的WCF服务中使用以下代码来调用另一个可能是也可能不是WCF服务的Web服务。

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

So I want to have some information in a xml file from which i read the various services endpoints and want to pass the binding information to the channel factory and call the other services based on the information i have in the config XML file. 所以我希望在xml文件中有一些信息,我从中读取各种服务端点,并希望将绑定信息传递给通道工厂,并根据配置XML文件中的信息调用其他服务。

So i want to generate the channel factory dynamically using different service contract information every time. 所以我想每次使用不同的服务合同信息动态生成通道工厂。

Is it possible in channel factory since various services have different Interfaces? 是否可以在渠道工厂中使用各种服务具有不同的接口?

In other words from the code above I have IService1 but when i read another service information from an xml file I want to create a channel with another Interface? 换句话说,从上面的代码我有IService1但是当我从xml文件中读取另一个服务信息时,我想用另一个接口创建一个通道?

Yes, it is possible through 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();
}

And the GetServiceEndpoint method to return the endpoint based on the type of T: 并且GetServiceEndpoint方法根据T的类型返回端点:

private static string GetServiceEndpoint(Type service)
{
    string serviceTypeName = service.Name;

    // Code to get and return the endpoint for this service type
}

Note that in this case, I expect the config file to have an endpoint associated with the service type name (eg IService1 and http://localhost/Service1.svc ). 请注意,在这种情况下,我希望配置文件具有与服务类型名称关联的端点(例如IService1http://localhost/Service1.svc )。

And finally to use it: 最后使用它:

IService1 serviceProxy1 = CreateProxyChannel<IService1>();
serviceProxy1.MyMethod();

IService2 serviceProxy2 = CreateProxyChannel<IService2>();
serviceProxy2.AnotherMethod();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM