gpt4 book ai didi

wcf服务已知类型属性问题

转载 作者:行者123 更新时间:2023-12-04 22:16:53 26 4
gpt4 key购买 nike

我想添加一个服务行为(或任何你建议的),它会自动将类型从 dll 插入到服务已知类型的服务中

这可能吗?如何?

最佳答案

已知类型属性被传递给 DataContractSerializer 构造函数。你可以customize the way this serializer is instantiated并将已知类型提供给 constructor通过反射(reflect)您的程序集并查找从基类派生的所有类型来分析序列化程序。

这是一个示例代码(未测试):

[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;
}
}

关于wcf服务已知类型属性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1121312/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com