views:

60

answers:

2

Is it possible for a .NET web service to accept an immutable object (or an object containing references to immutable objects) in a web method?

For example, if this is my web service method:

public class MyWebService : System.Web.Services.WebService
{
    [WebMethod]
    public void SetStatus(StatusData data)
    {
        // do something
    }
}

and StatusData contains an immutable property, Server will throw a System.Web.Services.Protocols.SoapException when method is called:

Unable to generate a temporary class (result=1).
Error CS0200: Property or indexer 'TestProject.Entities.StatusData.Id' cannot be assigned to -- it is read only

Can I still use immutable objects somehow, or is the only way to do it to map everything into mutable DTOs?

[Edit]

Obviously, I am not talking about strings, since string is a base type in .Net, and is really an exception to this problem. For example, XmlSerializer will not work (without explicit IXmlSerializable implementation) for any other immutable class.

But I was hoping that I could avoid manually writing a bunch of mutable DTOs (although the actual mapping can be automated).

A: 

Yes and this can be quickly demonstrated. Web services can accept strings which are immutable hence web services can accept immutable data.

What you're asking appears to be a slightly different question though. Can the web service serialization mechanism (XML serialization) handle an immutable object. Generally speaking no it cannot as XML serialization is based heavily on read/write properties which are not present on an immutable object.

Typically when I run into this situation I create 2 objects.

  1. My normal immutable object for use in the majority of circumstances
  2. A mutable version of my object which can easily be converted to and from the immutable version and is to be used in situations like serialization.
JaredPar
A: 

Well, it seems that there is no way but to use mutable DTOs for SOAP, so we used DTOs and AutoMapper to convert from immutable objects automatically.

Groo