Peladao
Peladao

Reputation: 4090

How to *properly* use interface types with WCF?

More specifically, the question is: How to serialize a class with WCF that has (must have) interface types in property signatures because it implements an interface?

This is a design question. I'm not looking for a hack. The purpose is to keep the interface definitions separate from implementing classes and hence not let interfaces refer to implementing classes.

I know that we're not supposed to pass around interfaces with WCF and also that there are still (non-interoperable) ways to do it (like using NetDataContractSerializer or the ServiceKnownType attribute), but that leaves me with the question: is there a proper way to use classes based on interfaces with WCF or should this not be attempted at all?

Upvotes: 3

Views: 762

Answers (2)

Peladao
Peladao

Reputation: 4090

I found a solution to my own specific problem.

The problem was that I was marking the properties (of an interface type) as DataMember. By instead marking corresponding private members as DataMember (and make sure that their types are concrete classes) the problem is solved.

Example:

[DataContract()]
public class Company : ICompany
{
    [DataMember(Name = "Employees")]
    private EmployeeList _employees;

    public IEmployeeList Employees { get { return _employees; }}
}

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062502

Serialization is fundamentally about transporting data. Interfaces are about describing behaviour. Fundamentally these two things are completely orthogonal, IMO.

You can possibly make it work with [KnownType(...)] - and it would certainly help if you were using the same exact types at each end (assembly sharing), but this is very non-portable.

If you are after the idiomatic WCF usage for portability, you should probably restrict yourself to simple data contracts, which stand a chance of being useful to clients who know only the WSDL.

That said, I have no qualms torturing and abusing WCF to my own ends when it suits me ;p

Upvotes: 4

Related Questions