WCF: Interfaces, Generics and ServiceKnownType

后端 未结 5 1547
隐瞒了意图╮
隐瞒了意图╮ 2020-12-16 03:59

I have the following:

[ServiceContract]
[ServiceKnownType(typeof(ActionParameters))]
[ServiceKnownType(typeof(SportProgram))]
[ServiceKnownType(typeof(Action         


        
5条回答
  •  北荒
    北荒 (楼主)
    2020-12-16 04:36

    It's an old question and even though the accepted answer is totally correct, I stumpled upon this in the search for a similiar problem and thought I could share my experiences. It's often a headache, but it is possible to use generics combined with interfaces with WCF. Here's a working example of another (similiar) implementation that I've done:

    [ServiceContract]
    [ServiceKnownType(typeof(CollectionWrapper))]
    public interface IService : 
    {
        [OperationContract]
        ICollectionWrapper FindAssociation(string name, int pageSize, int page);
    }
    
    public interface ICollectionWrapper
    {
        int TotalCount { get; set; }
        IEnumerable Items { get; set; }
    }
    
    [KnownType(typeof(OrganizationDto))]
    [KnownType(typeof(CompanyDto))]
    public class CollectionWrapper : ICollectionWrapper
    {
        [DataMember]
        public int TotalCount { get; set; }
        [DataMember]
        public IEnumerable Items { get; set; }
    }
    
    public class CompanyDto :  IAssociation
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
    public class OrganizationDto :  IAssociation
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    

    The key here is to use the combination of KnownType and ServiceKnownType.

    So in your case you can do something like this:

    [ServiceContract]
    [ServiceKnownType(typeof(ActionParameters))]
    [ServiceKnownType(typeof(ActionResult))] // Actual implementation of container, but interface of generic.
    public interface ISportProgramBl  
    {
        [OperationContract]
        IActionResult Get(IActionParameters parameters);
    }
    
    [KnownType(typeof(SportProgram))] // Actual implementation here.
    public class ActionResult
    {
        // Other stuff here
        T FooModel { get; set; }
    }
    

    This will work if you have a shared contract (access to the actual service interface) and consume the contract with ChannelFactory. I do not know if it works with a service-reference.

    However, there seems to be some issues with the implementation as mentioned here:

    WCF With a interface and a generic model

    And another similiar question asked and answered here:

    Generic return types with interface type params in WCF

提交回复
热议问题