samedi 30 octobre 2021

Can't figure out which code design pattern to use

I'm building an .NET CORE 3.1 API and there is controller method which receives XElement from body. XElement is SOAP Envelope but envelopes body content can be A B C or D DTOs, totally from each other different by their content.

Envelopes DTO body snippet DTO looks like this:

    /// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("Pasted XML", "0")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public partial class EnvelopeBody
{
    private object bodyContentField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(nameof(A), typeof(A), Namespace = "namespace")]
    [System.Xml.Serialization.XmlElementAttribute(nameof(B), typeof(B), Namespace = "namespace")]
    [System.Xml.Serialization.XmlElementAttribute(nameof(C), typeof(C), Namespace = "namespace")]
    [System.Xml.Serialization.XmlElementAttribute(nameof(D), typeof(D), Namespace = "namespace")]
    public object BodyContent
    {
        get
        {
            return this.bodyContentField;
        }
        set
        {
            this.bodyContentField = value;
        }
    }
}

When the controller method is called I receive Envelope I can deserialize it and see the content of for example A, B,C or D, depending of Envelope body content.

Further I need to recognize which one is which and call proper logic class depending on received message A, B, C or D to do other operations for particular message. How can I do this recognition and calling appropriate A, B, C or D logic in a right way? Could it be Factory design pattern?

Somehow don't feel that this is the best way:

        [HttpPost]
    public async Task ProcessEnvelope([FromBody] XElement envelopeMessage)
    {
        var xmlSerializer = new XmlSerializer(typeof(Envelope));
        using var stringReader = new StringReader(envelopeMessage.ToString());
        Envelope envelope = (Envelope)xmlSerializer.Deserialize(stringReader);

        if (envelope.Body.BodyContent is A contentA)
        {
            _logicA.Map(contentA);
        }

        if (envelope.Body.BodyContent is B contentB)
        {
            _logicB.Map(contentB);
        }
    }

Aucun commentaire:

Enregistrer un commentaire