Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize Generic type over WCF Service

Tags:

c#

wcf

I have a C# class defined as follows:

public class GenericItem<T>
{
  public List<T> Items { get; set; }

  public DateTime TimeStamp { get; set; }
} 

I am creating an instance of this class on my server. I am then trying to pass it over the wire via a WCF service as shown here:

[OperationContract]
public GenericItem<MyCustomType> GetResult()
{
  GenericItem<MyCustomType> result = BuildGenericItem();
  return result;
}

Everything compiles just fine at this point. When I "update service reference" in my Silverlight app an re-compile, I receive a compile-time error, similar to the following:

MyNamespace.GenericItemOfMyCustomType[extra chars] does not contain a public definition for 'GetEnumerator'

I have no idea why:

  1. Extra chars are appearing. The seem to change everytime I update the service reference.
  2. How to actually fix this.

What am I doing wrong?

like image 707
JavaScript Developer Avatar asked May 08 '12 14:05

JavaScript Developer


3 Answers

Sleiman is correct, but one can use Bounded Generics as described in this article, and you may be able to achieve what you want. This allows you to create a generic type within the service and expose it. But the consumer will not view it as generic as the type is specified in the service operation.

like image 59
ldgorman Avatar answered Oct 29 '22 18:10

ldgorman


You cannot define WCF contracts that rely on generic type parameters. Generics are specific to .NET, and using them would violate the service-oriented nature of WCF. However, a data contract can include a collection as a data member because WCF offers dedicated marshaling rules for collections.

like image 29
Sleiman Jneidi Avatar answered Oct 29 '22 20:10

Sleiman Jneidi


As sleiman has pointed out, Generics are not supported in SOAP.

WCF and generics -> http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/79585667-6b97-4ce4-93fa-3a4dcc7a9b86

related question -> WCF. Service generic methods

like image 1
Tilak Avatar answered Oct 29 '22 20:10

Tilak