Abdul Samad
Abdul Samad

Reputation: 5938

creating private data members in WCF service

Is it a good idea to create private data members in WCF service and if it is a good practice then when/where we initilize these member variable as the client is only calling methods of the service.

Upvotes: 0

Views: 1675

Answers (2)

Phil Degenhardt
Phil Degenhardt

Reputation: 7274

If you have any interest in interoperability, I dont't believe it is generally a good practice.

First a contract (operation contract, message contract, data contract , etc.) is created to specify, in an unambiguous way, what is supported and what is not. It explicitly specifies those things publicly. It gets very confusing, very quickly, when you start declaring private members to be part of a public contract. It becomes problematic for the programmer who comes after you to discern what is going on.

You are likely attempting to encapsulate logic in your data contracts, which is not the purpose of a data contract. As suggested by @CodeCaster, such manipulation should be performed outside the data contract class. Even simple things like constructors populating default values can be problematic. Such logic should also be performed outside the DataContract class.

In addition, when you declare private members to be [DataMember]s you are relying on a non-standard implementation detail of the data contract serialiser - the fact that it can read/write members that are not public - i.e. the DataConstractSerializer (at least on the .NET platform) can do things you couldn't do in your own code. You are depending on 'magic'. While this 'magic' helps DataConstractSerializer to deliver amazing performance, I don't think you should be depending on its implementation details. For example, you will find that such DataContract classes cannot be shared with Silverlight applications because on that platform the DataConstractSerializer cannot read/write non-public members.

However, like all 'practices', you have to consider your circumstances. If interoperability and maintainability are not a requirement, then most of the above is not relevant and can be disregarded. :)

Upvotes: 0

CodeCaster
CodeCaster

Reputation: 151664

Use your data contracts merely as DTO's, and extend these in the code that does the processing of the data.

Something like this:

[DataContract]
public class WCFDataClass
{
    [DataMember]
    public String Foo { get; set; }
}

// Your class, used for internal processing
class MyWCFDataClass : WCFDataClass
{
    public String MyFoo { get; set; }

    public String DoFoo()
    {
        return this.Foo + this.MyFoo;
    }
}

Upvotes: 1

Related Questions