Search code examples
c#fluent

Fluent interface issue with adding multiple elements


I have the following code (from mailgun_csharp):

var message = new MessageBuilder()
            .SetSubject(Subject)
            .SetFromAddress(new Recipient { Email = From.Address, DisplayName = From.DisplayName })
            .SetHtmlBody(Body)
            .AddToRecipient(new Recipient { Email = "a@a.com", DisplayName = "a" })
            .GetMessage();

so far, so good...

now I want to add 2 recipients:

var message = new MessageBuilder()
            .SetSubject(Subject)
            .SetFromAddress(new Recipient { Email = From.Address, DisplayName = From.DisplayName })
            .SetHtmlBody(Body)
            .AddToRecipient(new Recipient { Email = "a@a.com", DisplayName = "a" })
            .AddToRecipient(new Recipient { Email = "b@a.com", DisplayName = "b" })
            .GetMessage();

this works well too...

but if I have a List and I want to add the whole list to .AddRecipient, how can I do that programmatically?


Solution

  • It looks like mailgun_csharp library lacks a method for passing a list of recipients to the API. C# lets you fix this shortcoming by adding your own implementation as an extension:

    public static class MessageBuilderExtensions {
        public static IMessageBuilder AddToRecipients(
            this IMessageBuilder builder
        ,   IEnumerable<IRecipient> recipients
        ,   JObject recipientVariables = null) {
            foreach (var recipient in recipients) {
                builder = builder.AddRecipient(recipient, recipientVariables);
            }
            return builder;
        }
    }
    

    Now you can write this code:

    IEnumerable<IRecipient> myListOfRecipients = ...
    var message = new MessageBuilder()
        .SetSubject(Subject)
        .SetFromAddress(new Recipient { Email = From.Address, DisplayName = From.DisplayName })
        .SetHtmlBody(Body)
        .AddToRecipients(myListOfRecipients)
        .GetMessage();