2009-07-13 56 views

回答

7

已知的類型屬性被傳遞給DataContractSerializer構造函數。您可以customize the way this serializer is instantiated並通過反射您的程序集並查找從基類派生的所有類型,爲序列化程序的constructor提供已知類型。

下面是一個示例代碼(未測試):

[ServiceContract] 
public interface FooContract 
{ 
    [OperationContract] 
    [KnownTypesDataContractFormat(typeof(SomeBaseType))] 
    void MyOperation(SomeBaseType arg); 
} 

public class KnownTypesDataContractFormatAttribute : Attribute, IOperationBehavior 
{ 
    public Type BaseType { get; private set; } 
    public KnownTypesDataContractFormatAttribute(Type baseType) 
    { 
     BaseType = baseType; 
    } 

    public void AddBindingParameters(OperationDescription description, BindingParameterCollection parameters) 
    { } 

    public void ApplyClientBehavior(OperationDescription description, System.ServiceModel.Dispatcher.ClientOperation proxy) 
    { 
     IOperationBehavior innerBehavior = new KnownTypesDataContractSerializerOperationBehavior(description, BaseType); 
     innerBehavior.ApplyClientBehavior(description, proxy); 
    } 


    public void ApplyDispatchBehavior(OperationDescription description, System.ServiceModel.Dispatcher.DispatchOperation dispatch) 
    { 
     IOperationBehavior innerBehavior = new KnownTypesDataContractSerializerOperationBehavior(description, BaseType); 
     innerBehavior.ApplyDispatchBehavior(description, dispatch); 
    } 

    public void Validate(OperationDescription description) 
    { } 
} 

public class KnownTypesDataContractSerializerOperationBehavior : DataContractSerializerOperationBehavior 
{ 
    public Type BaseType { get; private set; } 
    public KnownTypesDataContractSerializerOperationBehavior(OperationDescription operationDescription, Type baseType) : base(operationDescription) 
    { 
     BaseType = baseType; 
    } 

    public override XmlObjectSerializer CreateSerializer(Type type, string name, string ns, IList<Type> knownTypes) 
    { 
     return new DataContractSerializer(type, name, ns, knownTypes); 
    } 

    public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList<Type> knownTypes) 
    { 
     return new DataContractSerializer(type, name, ns, knownTypes); 
    } 

    private IEnumerable<Type> GetKnownTypes() 
    { 
     // Try to find all types that derive from BaseType in the 
     // executing assembly and add them to the knownTypes collection 
     return 
      from type in Assembly.GetExecutingAssembly().GetTypes() 
      where type != BaseType && BaseType.IsAssignableFrom(type) 
      select type; 
    } 
} 
+0

我很抱歉我在WCF漂亮燈芯,如何使這上不是每個方法整個服務? – 2009-07-13 19:29:04