Using Interfaces With WCF

守給你的承諾、 提交于 2019-12-01 22:01:47

If your data contracts are interfaces WCF can't know what object to instantiate for an incoming request. There is no need for the class to be the same as in the service, after all the Add Service Reference reads the WSDL and generates new classes based on the type info in the WSDL.

This blog gives me the right direction to find the solution for my problem. Actually I have exactly the same scenario like sliderhouserules describes in his post.

But in my scenario I can't use any abstract or base class to inherit from. So I used a TypesHelper class to read the dataContractSerializer section by myself and pass the relevant types to the WCF service.

namespace ExampleNamespace
{
  public interface IJustAInstance { }

  [ServiceContract]
  [ServiceKnownType("GetKnownTypes", typeof(ExampleNamespace.TypesHelper))]
  public interface ICreateInstance
  {
    IJustAInstance CreateInstance();
  }

  public static class TypesHelper
  {
    public static IEnumerable<Type> GetKnownTypes(ICustomAttributeProvider provider)
    {
      DataContractSerializerSection section = (DataContractSerializerSection)
        ConfigurationManager.GetSection(
        "system.runtime.serialization/dataContractSerializer");
      if (dataContractSerializerSection != null)
      {
        foreach (DeclaredTypeElement item in dataContractSerializerSection.DeclaredTypes)
        {
          foreach (TypeElement innterItem in item.KnownTypes)
          {
            Type type = Type.GetType(innterItem.Type);
            if (typeof(IJustAInstance).IsAssignableFrom(type ))
              yield return type;
          }
        }
      }
    }
  }
}

You could create a BaseContract that your ClientContract and ServerContract can provide (as property) and that you can use in the respective constructor when creating new instances of the ClientContract or ServerContract. Then you only have to add the BaseContract to your shared lib.

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