views:

361

answers:

3

Hey Folks, Looking for some guidance on a WCF service I’m prototyping.

I have a WCF service hosted in IIS that will pass data to my clients. I have a separate shared assembly that contains all my business objects that is referenced in my WCF project.

I want to have a few of the properties in these business objects read only as I don’t want my customers to be able to change these fields in their client code.

I read that decorating classes with the [DataContract] attribute enforces the proper serialization to maintain readonly fields but when I implement it the proxy classes generated in the client show as writable.

Are there any tricks to accomplish this?

Thanks!

/Eric

A: 

Check out this topic.

BennyM
A: 

In my experience, I have found that the WCF serializer works nicely with only very simple object models. If you planning on passing your business or domain objects over the wire, you may want to consider creating stand in "transfer" objects. This object will give you control over exactly what your consumers are receiving and can be mapped back to your domain objects.

pattersonc
A: 

You can use regular properties, mark them with the DataMember attribute and make the set accessor private:

        [DataMember]
        public object IsFoo
        {
            get
            {
               return _isFoo;
            }
            private set { }
        }

EDIT: Also, to truly prevent users of your class from setting the property, you could always throw an InvalidOperation exception.

Philip Wallace
So I tried this route (below) but when I get into the client and work with the proxy object I can still "set" the value. private string strAdUrlTec; [DataMember] public string AdUrlTec { get { return strAdUrlTec; } private set { } }
Eric
How are you setting the property? And from where - is it inside the owning class? You should get a compile error if it is outside!
Philip Wallace
I'm not setting it from the owning class. I have a WCF service project that referances an outside assembly where my business objects live(specifically the one we're talking about). I have a unit testing project that consumes the WCF service. So in my unit test I pull down an object from the WCF service and then change the AdUrlTec property and it lets me. I saw another thread last week with your same solution so I think you're right but I'm wondering why my implementation isn't honoring the private setter. :(
Eric
The only thing I can think of is that the unit testing module sets the property using reflection - which does allow you to bypass the private modifier...
Philip Wallace
Also, in the sample you posted in your first comment - even if someone does set the property, it won't actually do anything as the set accessor is empty. Another solution would be to throw an exception in the set accessor.
Philip Wallace
Thanks Philip. Good suggestions. I'll investigate those solutions.
Eric