Multiple instances of same interface in Azure Functions
    • Dark
      Light
    • PDF

    Multiple instances of same interface in Azure Functions

    • Dark
      Light
    • PDF

    Article Summary

    #ServerlessTips - Azure Functions
    Author: Mandar Dharmadhikiri Business & Integration Architecture Manager

    There can be cases while developing Azure Functions where you might want to use the different implementations of an interface to achieve different functionality e.g., you might be writing a serverless notification microservice that is responsible for sending SMS, and WhatsApp notifications for the order placed by the customer.

    .NET core provides a simple dependency injection pattern, which you can use for this scenario.

    Start by adding an interface for the notification service as shown below

    download 100

    For sake of simplicity the SMS and WhatsApp implementation look like below
    download - 2023-07-21T130220.636

    download - 2023-07-21T130343.818

    You can now register both the implementations in the Startup class as shown in following screenshot

    download - 2023-07-21T130447.983

    The dependency injection will be a bit different, and you will have to use the IEnumerable to inject all the registered instances of the interface. It can be done as shown below

    download - 2023-07-21T130447.9831

    The implementations then can be simply invoked as shown

    download - 2023-07-21T134226.537

    The function code can iterate through the collection of the implementations and the result will be as shown below:

    download

    This nifty pattern can be used with any number of implementations of the interface as required.

    MicrosoftTeams-image 442


    Was this article helpful?