服务合同中的WCF多态性

时间:2014-03-10 01:00:39

标签: wcf serialization polymorphism

我正在尝试使用一个操作来创建一个服务,该操作接受一个实现特定接口的任何对象作为参数。我本以为这很容易实现,但我遇到了问题(我猜测是序列化问题,但我不确定)。我有以下合同:

//Unsustainable because I would need a method for each of the (currently)
//3 student types, plus I have 2 more root categories that have multiple subtypes
public interface IEmailTemplateAccess
{

    [FaultContract(typeof(ValidationFault))]
    [FaultContract(typeof(ErrorResponse))]
    [OperationContract]
    [TransactionFlow(TransactionFlowOption.Allowed)]
    TemplateResponse GetStudentTemplate(ITemplateRequest request);

}

这就是我希望它的样子:

public interface IEmailTemplateAccess
{

    [FaultContract(typeof(ValidationFault))]
    [FaultContract(typeof(ErrorResponse))]
    [OperationContract]
    [TransactionFlow(TransactionFlowOption.Allowed)]
    TemplateResponse GetTemplate(ITemplateRequest request);

}

在我的服务中,我使用抽象工厂根据请求的类型返回正确的模板。此外,我已经为可以返回的不同类型的模板创建了具体的ITemplateRequests。例如,我有模板请求类型A和B.模板请求类型A可以有3种子类型之一,SubType1,SubType2和SubType3。然后我创建了一个实现ITemplateRequest接口(SubType3Request)的SubType3请求。

我不想为我拥有的每个请求类型(即GetSubType1Template,GetSubType2Template,GetSubType3Template,GetTypeBTemplate等)创建一个方法,因为这会很快变得难以处理,因为我可以获得的模板类型偶尔会发生变化。

有没有办法让一个契约方法接受任何实现ITemplateRequest作为参数的东西,并让我的工厂去搞清楚要获得什么类型的模板?

到目前为止,我的服务中有以下方法:

    //Not a part of the contract right now although I would like it to be
    public IEmailTemplate GetTemplate(ITemplateRequest request)
    {
        TemplateFactoryBuilder builder = new TemplateFactoryBuilder();
        ITemplateFactory factory = builder.GetTemplateFactory(request.Type);
        var template = factory.GetTemplate(request);
        return template;
    }

    //contract method --This would be my Parent Request Type (RequestTypeA) from above. 
    //There are 3 subtypes of the Student type
    public TemplateResponse GetStudentTemplate(StudentEmailTemplateRequest request)
    {
        var response = new TemplateResponse
                           {
                               RequiresProcessing = true
                           };


        response.Template = (EmailMergeTemplate) GetTemplate(request);
        return response;
    }

1 个答案:

答案 0 :(得分:2)

很抱歉链接回答,但它很长..你所追求的(我认为)就在这里:http://blogs.msdn.com/b/morgan/archive/2009/08/05/polymorphism-in-wcf.aspx

归结为使用已知类型。像这样的东西;

[ServiceContract]
[ServiceKnownType("GetKnownTypes", typeof(CommandServiceHelper))]
public interface ICommandService