Matt Winward
Matt Winward

Reputation: 1255

Can I inherit my WCF DataContract from a shared interface?

I have a WCF service and client in the same solution (different projects). The service class itself inherits from an interface, and that interface is shared between client and server (via a linked file). The client uses a service factory to generate a proxy. This has proved a really nice way to link the two sides without referencing the server-side project from the client.

One of the service methods returns an object that includes the DataContract and DataMember attributes, and until recently this class was linked to the client as well, but the server-side logic was excluded from the client using compilation symbols.

I decided it would be more sensible to turn this into an interface as well. But now I get the following exception every time the service method is called from the client:

The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.

Its inner exception is as follows:

Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

So by way of simplified example, my service essentially shares the following interface with the client:

public interface IMyData
{
    [DataMember]
    int Id {get; set;}

    [DataMember]
    string Description {get; set;}
}

The actual object that the interface works with and will return looks something like this:

[DataContract]
public class MyData : IMyData
{
    [DataMember]
    public int Id {get; set;}

    [DataMember]
    public string Description {get; set;}
}

The interface of my service looks something like this:

[ServiceContract]
public interface IMyService
{
    [OperationContract]
    IMyData GetData();
}

The implementation looks something like this:

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.Single)]
public class MyService : IMyService
{
    [OperationContract]
    IMyData GetData()
    {
        // Get data.
    }
}

Hope that all makes a little sense! I'm just wondering if I'm doing this all wrong. I'll just go back to sharing the class and sectioning off the server-side-only code if I have to .. but I'd rather use an interface if I can.

Any ideas?

Upvotes: 2

Views: 1014

Answers (1)

aqwert
aqwert

Reputation: 10789

There is no benefit to putting an interface on a DataContract as they simply represent data and no logic. You typically put those DataContracts inside the same assembly with the ServiceContracts or a separate assembly all together. This will prevent exposing the business logic to your clients.

Upvotes: 3

Related Questions