简体   繁体   English

如何使用自定义序列化WCF?

[英]How to use custom serialization WCF?

Has any one ever implemented a custom serializer in WCF ? 有没有人在WCF中实现过自定义序列化程序? The reason i want to replace the WCF default serializer with custom serializer is to call different services from the same wcf proxy client.I would be glad if some one can suggest a way to do this ? 我想用自定义序列化程序替换WCF默认序列化程序的原因是从同一个wcf代理客户端调用不同的服务。如果有人可以提出一种解决方法,我会感到高兴。

I did something similar on a project I recently did. 在最近完成的一个项目中,我做了类似的事情。

However I did have 2 different WCF clients. 但是我确实有2个不同的WCF客户端。 How I "switched" was I then created a shared interface between the clients and then used a ServiceLocator to fetch the IClient . 然后,如何“切换”我在客户端之间创建一个共享接口,然后使用ServiceLocator来获取IClient

Does this make sense? 这有意义吗?

If I understand the problem correctly you have an application that you want to talk to one of two services that use the same interface based on some criteria. 如果我正确理解了问题,则您有一个应用程序想要与基于某些条件使用同一接口的两个服务之一进行对话。 The services have different configurations so you cannot reuse the same config. 这些服务具有不同的配置,因此您不能重复使用相同的配置。

To tackle this I would setup the two configurations in the application config, it could also be done in code if you wish. 为了解决这个问题,我将在应用程序配置中设置两个配置,如果您愿意,也可以用代码完成。

<client>
  <endpoint address="http://service1"
            binding="basicHttpBinding"
            bindingConfiguration="Service1Binding"
            behaviorConfiguration="Service1Behavior"
            contract="IServiceInterface, Service"
            name="Service1"/>

  <endpoint address="http://service2"
            binding="basicHttpBinding"
            bindingConfiguration="Service2Binding"
            behaviorConfiguration="Service2Behavior"
            contract="IServiceInterface, Service"
            name="Service2"/>
</client>

In your code you then need some sort of conditional statement to determine which service you want to talk to. 然后,在代码中,您需要某种条件语句来确定您要与之对话的服务。 Once you have done this you can create a ChannelFactory for the required configuration. 完成此操作后,您可以为所需的配置创建ChannelFactory

string serviceName = FullMoon ? "Service1" : "Service2";

var channelFactory = new ChannelFactory<IServiceInterface>(serviceName);

var proxy = channelFactory.CreateChannel();

proxy.SomeServiceCall();

channelFactory.Close();

If you are using IoC to inject the proxy you will probably need to push this into some sort of factory. 如果使用IoC注入代理,则可能需要将其推送到某种工厂中。 You can also look at optimizing this as creating the ChannelFactory is the expensive part, it is possible to create the Factory without specifying the configuration just the contract. 您还可以查看优化这一点,因为创建ChannelFactory是昂贵的部分,可以在不指定配置而仅指定合同的情况下创建Factory。 You would then need to specify the binding and the endpoint when you create the channel. 然后,您需要在创建通道时指定绑定和端点。

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

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