WCF Known Type from System.Object in Config

前端 未结 2 1048
走了就别回头了
走了就别回头了 2020-12-16 21:49

I\'m trying to specify a known type in my config, but I\'m having problems with the fact that it derives from Object. I can make it work specifying the known type via attrib

2条回答
  •  囚心锁ツ
    2020-12-16 22:34

    The answer turns out to be it's not possible to do what I want to do in the config file alone. The config above corresponds to the [KnownType] attribute used on DataContracts. There appears to be no way to implement [ServiceKnownType] in the config.

    An alternate approach is to use [ServiceKnownType(methodName, type)] attribute with a custom configuration section. The new config looks like this:

    
      
        

    The contracts:

    [ServiceContract]
    [ServiceKnownType("GetServiceKnownTypes", typeof(KnownTypeHelper))]
    public interface IContract
    {
        [OperationContract]
        void Send(object data);
    }
    
    [DataContract]
    public class MyData
    {
        [DataMember]
        public string Message { get; set; }
    }
    

    The helper class that contains the callback that returns the list of known types

    public static class KnownTypeHelper
    {
        public static IEnumerable GetServiceKnownTypes(ICustomAttributeProvider provider)
        {
            List result = new List();
    
            ServiceKnownTypesSection serviceKnownTypes = (ServiceKnownTypesSection)ConfigurationManager.GetSection("serviceKnownTypes");
            DeclaredServiceElement service = serviceKnownTypes.Services[((Type)(provider)).AssemblyQualifiedName];
    
            foreach (ServiceKnownTypeElement knownType in service.KnownTypes)
            {
                result.Add(knownType.Type);
            }
    
            return result;
        }
    }
    

    Information on creating custom config sections can be found here:

    http://msdn.microsoft.com/en-us/library/2tw134k3.aspx

    http://msdn.microsoft.com/en-us/library/system.configuration.configurationcollectionattribute.aspx

提交回复
热议问题