How can I send an IList via WCF Service?
I want to use N开发者_开发技巧Hibernate in my WCF service, How can I send an IList via WCF Service?
---EDIT-------
Can I put the IList in an object
variable and send it?
Trying to pass an IList<T>
isn't really appropriate for a WCF-based service.
WCF talks in terms of data contracts, defining the shape of the data a service or client will expect to send and receive. These contracts have to be concrete enough for serializers to know how to convert them into XML, JSON and other representations.
When you put an interface like IList<T>
into your service contracts, you aren't giving the serializer enough information about the specified shape of your data. Do you care just about sending the IList<T>
part of the implementation? Are you interested in any of the other stateful data contained by something implementing the interface? The serializers have no way of knowing.
The simplest solution is to use basic data-transfer objects with WCF. These are simple classes which only have the job of representing information to be transmitted over a medium. These classes contain only concrete types and are easily understood by serializers. When you want to send a message you create instances of these objects and populate them with data.
For your example, create List<T>
instead of IList<T>
and copy the values into the list prior to passing it into the service. A simple way to do this is with the Enumberable.ToList<T>()
extension method.
The serializer needs to know the concrete type so annotate the contract with [ServiceKnownType] so it knows what types could be used for the IList
Update: object doesn't help as the serializer still doesn't know what to do - you will need to tell it using [ServiceKnownType] - you can supply a method here that returns the list of types if you don't want to be explicit at compile time
You need to use generics and mark what type of list it is so the service knows what to expect. A method can look like this:
public IList<Something> GetSomething()
That said, when I do this I tend to return an array instead just because there's less guessing when reading the code later about exactly what it's going to return (does a non WCF client on the other end create an IList class for it or does it convert it into something else?). Everything knows what an array is.
Further to the concept of using List type
-- why not just use an array?
An array seems like the most obvious choice as it is compatible with IEnumerable and the client can use their own extension methods
精彩评论