RiskX
RiskX

Reputation: 591

Serializing interface in wcf

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?

Upvotes: 1

Views: 69

Answers (2)

Gerardo Lima
Gerardo Lima

Reputation: 6703

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.

Upvotes: 1

Joe Enos
Joe Enos

Reputation: 40393

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.

Upvotes: 1

Related Questions