开发者

WCF: Serialize complex objects with read-only members

开发者 https://www.devze.com 2022-12-10 18:46 出处:网络
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

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


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.


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.

0

精彩评论

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

关注公众号