[英]WCF serialization - convert to different type on the fly?
我有一个WCF服务接口,如下所示:
[ServiceContract(Namespace = "http://somenamespace", SessionMode = SessionMode.NotAllowed)]
public interface IRuntimeService
{
[OperationContract]
ISupporterProperties CreateOrModifySupporter(Guid id);
}
并且实现(在客户端和服务器上)如下所示(它是托管并以编程方式连接):
public IOwnerProperties CreateOrModifyOwner(Guid id)
{
//get an owner ...
//the owner is of type Owner which implements IOwnerProperties.
return theOwner;
}
但是,这里的问题是WCF将尝试以Owner
身份对此序列进行序列化或反序列化,因为这是返回的实际类型,但是我希望它作为OwnerDataContract
发送它,该对象也恰好实现了IOwnerProperties
。
换句话说,我想返回一个Owner
,但要使其序列化/反序列化为OwnerDataContract
。
我知道我可以为客户端的界面创建包装器类。 但是,我希望有尽可能多的共享代码。
对于AutoMapper来说,这是完美的工作。 如果Owner
和OwnerDataContract
具有相同的属性和字段,则设置非常简单
static void Main()
{
//Do this once at program startup
Mapper.CreateMap<Owner, OwnerDataContract>();
//Run the rest of your program.
}
如果由于展平或重命名而需要重新映射某些属性,将会有更多的设置工作,请参见Wiki以获取更多信息。
要使用映射,操作非常简单
public IOwnerProperties CreateOrModifyOwner(Guid id)
{
//get an owner ...
//Mapper.Map retuns a object of type OwnerDataContract
return Mapper.Map<OwnerDataContract>(theOwner);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.