Expose object from class library using WCF

Expose object from class library using WCF

成熟稳重的好男人 发布于 2021-11-29 字数 358 浏览 881 回复 2 原文

I'm using a class library that exposes a few objects. These objects have a couple of properties that hold data my clients need. I'd like to create a WCF service that returns the objects to my clients but I cannot update the class library in order to add the DataContract and DataMember attributes. What is the easiest way of exposing these objects?

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。



需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。


Spring初心 2022-06-07 2 楼

If you can't set the [DataContract] and [DataMember] attributes on your object, you'll have to find a way to expose them using the XmlSerializer.

You can define a service or an operation to use the XmlSerializer by specifying the [XmlSerializerFormat] attribute on either your Service contract, or an individual OperationContract.

Does that help maybe?


踏月而来 2022-06-07 1 楼

You can use a DataContractSurrogate.

...You can apply the DataContract
attribute to the Person class, but
this is not always possible. For
example, the Person class can be
defined in a separate assembly over
which you have no control.

Given this restriction, one way to
serialize the Person class is to
substitute it with another class that
is marked with DataContractAttribute
and copy over necessary data to the
new class. The objective is to make
the Person class appear as a
DataContract to the
DataContractSerializer. Note that this
is one way to serialize non-data
contract classes. ...