Object hierarchy returned by WCF Service is different than expected

牧云@^-^@ 提交于 2019-12-04 17:18:12

OK - default behavior for a WCF Service is this:

  • you define your service contracts, operations, and data contract on the server (e.g. in namespace "Server.MyService")
  • once the service is up and running, on your client, you create a service reference
  • when doing so, what Visual Studio or svcutil.exe do, is interrogate that service for its metadata (description of service methods and data)
  • based on that metadata, the client side proxy is generated (namespace "Client.MyService") and it contains replicas of the service contract (the methods) and the data contract

Important: it contains replicas of those things! They look the same, and they serialize into the same XML format on the wire - but they are different - in different namespaces, most notably.

This is the very nature of WCF - all you do is exchange serialized messages between client and server - all that goes back and forth are textual messages. Nothing more - no object references, no remote object - nothing like that. Toss that out of your mind! :-)

If you control both ends of the wire, this can be a pain - if you need to change anything, you have to change it on the server side, update the client references and so forth.

So if you control both ends of the wire - both the server and the client - and they're both .NET based, you can do the following:

  • put your service contracts and your data contracts (only the contracts - no implementations!) into a separate assembly
  • from your service implementation, reference that contracts assembly
  • copy the contracts assembly to your client, and also reference it in your client project

Now, if you add the service reference, by default, the Add Service Reference function in Visual Studio will reuse existing types in referenced assemblies - so if you have referenced your common "Contracts" assembly, those types (in their full glory, including their namespace) will be reused - no additional copies will be created.

That way, you can create a single, shared contracts assembly used by both the server side code, as well as your client, and you don't have to mess with any duplication of data structures. But again: that only works if you are in control of both ends of the wire, and both are .NET

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!