Serializing interface in wcf

空扰寡人 提交于 2020-01-05 04:16:12

问题


I designed an application that has an interface and two inherited classes:

interface IPerson {}
class Man:IPerson{}
class Woman:IPerson{}

Now, I wrote a method that looks like this:

public IPerson GetPeron(int idNumber);

This method gets an ID number and looks for that number in the DB. If that number belogns to a man, a new Man instance is created, data from the DB is being put into the new instance and finally the instance returns. The same goes if the given ID belongs to a woman

Now I want that method to be placed not on the client side but on a WCF server. The problem is that the return type can't be an Interface anymore.

The obvious solution is to create three methods:

A. Get an ID and return an enum that represent the person type:

enum PersonType { Man,Woman }
PersonType GetType(int personID);

B. Gets an ID and return a Man:

Man GetMan(int personID);

C. Gets an ID and return a Woman:

Woman GetWoman(int personID);

I think that's kind a lousy, any better suggestion?


回答1:


If it really is as simple as this example (no multiple implementation or other base classes involved), a base class instead of (or in addition to) an interface would work:

public interface IPerson { }

[KnownType(typeof(Man))]
[KnownType(typeof(Woman))]
public class BasePerson : IPerson { }

public class Man : BasePerson { }
public class Woman : BasePerson { }

[OperationContract]
BasePerson GetPerson(int value);

Your proxy will generate the base class and the concrete classes, so when you call:

var x = proxy.GetPerson(3);

x will be declared as type BasePerson, but the actual type of the object will be either Man or Woman.




回答2:


Unfortunatelly when working with WCF you cannot have interfaces, abstract base classes or classes without the default (empty) constructor. That bothered me a lot, but you have to choose between WCF and good OO practices...

The best I came to was to create auxiliary wcf-interfaceable concrete classes to use on WCF contracts and the operators I needed to implicit convert between their instances and the corresponding business classes.



来源:https://stackoverflow.com/questions/17729145/serializing-interface-in-wcf

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