Search code examples
c#azuremefazure-functionscomposition

Using MEF in an Azure function App


I am trying to use MEF in my function app. My requirement is to access 5-10 external APIs, fetch,aggregate and return the data through an HTTP triggered function. I need to resolve the external dependencies dynamically based on some logic. These external components are already built and exported. I need to import them along with metadata.

I observed that System.ComponentModel.Compositionassembly is already referenced in a default function app created in VS 2017. Not sure how to proceed. A sample setup code would be helpful if at all it is possible in Azure functions.


Solution

  • Based on your scenario, I created my Http Trigger function via VS2017 to test this issue. I followed the Simple Calculator MEF Application. And here is the structure of my project and as follows:

    enter image description here

    Without adding the extension lib which supports the Mod operation into the Extensions folder, you could retrieve the following result:

    enter image description here

    While added the ExtendedOperations.dll, the Mod operation could work as expected as follows:

    enter image description here

    On my local side, I added the path for initializing DirectoryCatalog via hard code. When deploying to azure side, your precompiled function lib would be deployed under D:\home\site\wwwroot\bin>, you could add your Extensions folder within it and use the following code for retrieving your extension folder:

    Path.Combine(System.Environment.GetEnvironmentVariable("HOME"), @"site\wwwroot\bin\<your-extensions-folder>")
    

    Also, you could leverage kudu and navigate to D:\home\site\wwwroot\<your-function-name>, then add your Extensions folder under it, then init your DirectoryCatalog with the path Path.Combine(System.Environment.GetEnvironmentVariable("HOME"), @"site\wwwroot\<your-function-name>\<your-extensions-folder>").

    enter image description here