How can I use generic methods in wcf service?
I wrote this code:
[OperationContract]
void AddItem<T>(T item);
But I receive the following Error:
Type 'T' cannot be exported as a schema type because it is an open generic type. You can only export a generic type if all its generic parameter types are actual types.
You simply can't. It's not possible to do that, as soap does not support this. See this article, which mentions how to get around generics, by creating an intermediate local object that is called and casts the object before calling the WCF operation.
You shouldn't be trying to do this. In a SOAP enabled web service all types need to be known when the WSDL is published so that clients would be capable of generating a proxy. Generics simply don't exist in the SOAP specification. SOAP is intended to be interoperable and generics don't exist in all languages.
As all the others have already mentioned, WCF and SOAP do not support this. The issue is: anything you pass back and forth between client and server must be expressible in a XML schema document.
XML schema supports all the usual atomic types, like string, int, datetime - and it supports complex types made up of those atomic types, and it supports inheritance.
But XML schema has no support for generics - and thus, anything you exchange via WCF and SOAP cannot be generic - you need to use concrete, non-generic types only.
I don't know of any way around this, either. It's a limitation and you have to live with it for now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With