How can I send an IList via WCF Service?

六眼飞鱼酱① 提交于 2019-12-11 07:19:07

问题


I want to use NHibernate 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?


回答1:


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.




回答2:


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




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/6730912/how-can-i-send-an-ilist-via-wcf-service

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!