开发者

WCF method that updates object passed in

开发者 https://www.devze.com 2022-12-25 01:21 出处:网络
Am I correct in thinking that if I have a WCF OperationContract takes in an object and needs to set a property on that object so the client gets the update, I need to declare it to return the object.

Am I correct in thinking that if I have a WCF OperationContract takes in an object and needs to set a property on that object so the client gets the update, I need to declare it to return the object.

e.g. given a datacontract:

[DataContract]
public class CompositeType
{
    [DataMember]
    public int Key { get; set; }

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

this will not work with WCF:

public void GetDataUsingDataContract(CompositeType composite)
{
  composite.Key = 42;              
}

this will work:

public CompositeType GetDataUsingDataContract(CompositeType composite)
{
  composite.Key = 42;

  return new CompositeType
  {
    Key = composite.Key,
    Something = composite.Something
  }; 开发者_StackOverflow          
}


IMO, authoring methods that produce output via side-effects is a "bad" thing. Having said that however, are there circumstances that necessitate this model? Yes.

Certainly C# programming model permits this, is WCF broken? No. At a certain point, one must realise they are consuming WCF, and as a framework it attempts to satisfy a majority of use-cases [for instance, replicating all input parameters on all round trips to preserve implicit side effect semantics is, in a word, silly].

Of course, there are ways to work around this - C# also provides for explicit declaration of these scenarios and WCF supports these as well!

For instance

// use of "ref" indicates argument should be returned to 
// caller, black-eye and all!
public void GetDataUsingDataContract (ref CompositeType composite) 
{
    composite.Key = 42;         
}

Give it a go!

Hope this helps :)


If you use 'out of the box' WCF, you are actually using a form of webservices, that uses serialized versions of the objects that are sent from client to server. This is the reason you cannot 'by reference' change properties on objects. You will always have to use a request / response pattern.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号