Search code examples
c#wcfgenerics

Passing Specified Generic Type through WCF Service


I have the following classes:

[DataContract]
[KnownType(typeof(SpecifiedItemCollection))]
public class ItemCollection<T> : IEnumerable where T : BaseItem
{
    private Dictionary<int, T> items = null;

    //Some NON-Generic Methods and Properties

    //Some methods like this:
    public T DoBla(int _1, bool _2) { ... }
}

[DataContract]
public class SpecifiedItemCollection : ItemCollection<SpecifiedItem>
{
    //...
}

[DataContract]
[KnownType(typeof(SpecifiedItem))]
public class BaseItem { ... }

[DataContract]
public class SpecifiedItem : BaseItem { ... }

How do I deliver SpecifiedItemCollection through a WCF Service?

My Interface looks like this, but unfortunately it won't work

[ServiceContract]
public interface IService
{
    [OperationContract]
    public SpecifiedItemCollection GetCol(int _1, bool _2);
}

And for additional information:

Yes, I saw that you can't pass Generic's through WCF (for example ItemCollection directly), but I found several sources that say you CAN pass them IF you specify the Generic itself.

So, what am I doing wrong? :)

The problem is, it simply closes the connection. I am able to reference the service in my project and it generates the needed Classes/Files accordingly. I can instantiate a MyServiceNameClient, but as soon as I'm calling a method from my service which will return an SpecifiedItemCollection, it closes the connection.


Solution

  • Seems like I found a temporary solution, although I do not like it very much.

    In my example above, change the SpecifiedItemCollection-Class as follows:

    [DataContract]
    public class SpecifiedItemCollection
    {
        public ItemCollection<SpecifiedItem> Base;
    
        public SpecifiedItemCollection()
        {
            Base = new ItemCollection<SpecifiedItem>();
        }
    
        //...
    }
    

    With this I am able to call the functions of ItemCollection and at the same Type have my SpecifiedItemCollection-Class with the extra Methods and Properties.

    If anyone has another solution, I'd be more than happy to see it. :)