Anantha
Anantha

Reputation: 215

Passing and retrieving a class with methods through WCF service

I want to pass/retrieve an instance of the following class through a wcf service. The object should carry the methods that are defined by its class also. is it possible? suppose the following class:

[DataContract]
public class MyClass
{
    [DataMember]
    public string Name;

    public MyClass()
    {

    }

    public MyClass(string name)
    {
        this.Name = name;
    }

    public void SetName(string name)
    {
        this.Name = name;
    }

    public string GetName()
    {
        return this.Name;
    }
}

[ServiceContract]
public interface IMyService
{
    [OperationContract]
    MyClass GetMyClassInstance();        
}

public class MyService:IMyService
{
    public MyClass GetMyClassInstance()
    {
        return new MyClass("hello");
    }
}

Now, when I add a reference to MyService in my client application project, the data contract MyClass will be generated, along with the service client, say MyServiceClient, so, and i do the following:

MyServiceClient client=new MyServiceClient();
MyClass myClass1= client.GetMyClassInstance();

But my real question is, after getting the result from the service, whether this is possible(?) :

myClass1.SetName("oops!!!");

while transmitting data contracts, will the methods in them also be transmitted? My Business objects contain methods too, and they need to be passed through WCF. Is there a way? Is passing BOs such as this through WCF a good practice? Thanks in advance!

Upvotes: 3

Views: 1294

Answers (2)

Buh Buh
Buh Buh

Reputation: 7546

The methods will not be passed by WCF, but then methods are fixed at compile time so it would be a bit odd to want to pass them around at runtime.

If you want the client object to have the same methods as the server object, the easiest way is to put your data contracts into their own project and then provide the resulting DLL to your client.

Then when the client generates the WCF proxy from your WSDL, they choose to reuse the known classes rather than generate new ones. To do this, when you add your service reference, click "Advanced" and then see the "Reuse types in referenced assemblies" options.

enter image description here

Upvotes: 0

lcryder
lcryder

Reputation: 496

WCF exchanges XML (or JSON) documents. The method values marked with 'DataMember' will be in the document. No code within a method is serialized.

Upvotes: 2

Related Questions