I have a WCF service that needs to expose a custom collection to it's clients. I wondered what would be 开发者_如何学Gothe best way to expose this object to my clients?
Object Code:
public class ListBoxDataCollection : System.Collections.CollectionBase
{
public ListBoxDataCollection()
{
}
public ListBoxData this[int index]
{
get { return (ListBoxData)this.List[index]; }
set { this.List[index] = value; }
}
public int IndexOf( ListBoxData item )
{
return base.List.IndexOf(item);
}
public int Add( ListBoxData item )
{
return this.List.Add(item);
}
public void Remove( ListBoxData item )
{
this.InnerList.Remove(item);
}
public void CopyTo( Array array, int index )
{
this.List.CopyTo(array, index);
}
public void AddRange( ListBoxDataCollection collection )
{
for (int i = 0; i < collection.Count; i++)
{
this.List.Add(collection[i]);
}
}
public void AddRange( ListBoxData[] data )
{
this.AddRange(data);
}
public bool Contains( ListBoxData item )
{
return this.List.Contains(item);
}
public void Insert( int index, ListBoxData item )
{
this.List.Insert(index, item);
}
}
Are you on .NET 3.5 or up? In that case, I would recommend List<ListBoxData>
which seems like the easiest way to go. WCF was no trouble at all with generic lists - worst case it'll model them as an array of ListBoxData
on the client.
If you own both ends of the communication, you could put the data contracts (and service contracts) into a shared assembly and use it on both ends, thus getting around this problem - in that case, you could use List<ListBoxData>
on both ends of the communication.
Marc
Decorating it with [DataContract] attribute.
Well, WCF is really not about exposing objects -- in fact, exposing an object/custom type violates the tenets of SOA
If you need the class to be available on both sides of your service boundary, you will need to provide a library that has that class defined in it that both the service and client can reference directly.
To transfer the data from the custom collection over WCF, the best practice would be to define data contracts/data contract collections that can be used to move the data (without any behavior), and to convert the data to/from your custom collection type on either side of the service call.
So when someone called the service, the service would convert the collection to a DataContract, provide it to the client, and the client would convert it into the custom collection.
I think it would be better if you just expose an array. Custom collection implies that there is some special functionality in it, like special sorting or behavior. SOA/WCF interface should contain only data, and not a behavior or functionality.
Exposing functionality over the wire in any distributed system is kind of antipattern. This forces potential clients that reside on other platforms to copy your code and this in it's turn violates the famous DRY (Don't Repeat Yourself) principle.
精彩评论