Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use interfaces as DataMembers in WCF?

Tags:

c#

interface

wcf

Can you do this?

[DataContract]
public class RegisterEndpointRequest : NotificationRegistrationServiceRequest
{
    [DataMember]
    public IEndpoint Endpoint { get; set; }
}

Notice the member Endpoint is an interface (IEndpoint), not a class. Will WCF allow this?

like image 491
Paul Fryer Avatar asked Aug 03 '12 16:08

Paul Fryer


People also ask

Can an interface have properties C#?

Like a class, Interface can have methods, properties, events, and indexers as its members. But interfaces will contain only the declaration of the members. The implementation of the interface's members will be given by class who implements the interface implicitly or explicitly.

What is Datacontract and DataMember in WCF?

A datacontract is a formal agreement between a client and service that abstractly describes the data to be exchanged. In WCF, the most common way of serialization is to make the type with the datacontract attribute and each member as datamember.

Can we create object of interface in C#?

Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible to create an "IAnimal" object in the Program class) Interface methods do not have a body - the body is provided by the "implement" class.

Is DataMember attribute required?

You must specify [DataMember] attribute on the property or the field of your Data Contract class to identify it as a Data Member. DataContractSerializer will serialize only those members, which are annotated by [DataMemeber] attribute.


1 Answers

I think you can (but I haven't tested it), but you will then need to declare all implementations of that interface with [KnownType]:

[DataContract]
[KnownType(typeof(EndpointImplA))]
[KnownType(typeof(EndpointImplB))]
public class RegisterEndpointRequest : NotificationRegistrationServiceRequest
{
    [DataMember]
    public IEndpoint Endpoint { get; set; }
}

Each implementing class must have a [DataContract] attribute.

like image 78
Aasmund Eldhuset Avatar answered Sep 30 '22 03:09

Aasmund Eldhuset