Precompiled functions

Fabio Cavalcante edited this page Jan 3, 2017 · 2 revisions

Azure Functions supports precompiled functions, which enables the use of .NET assemblies containing the function implementation, bypassing the dynamic compilation process.

In order to use precompiled functions, your function.json file must have the scriptFile and entryPoint properties set, pointing to the assembly file and fully qualified method name, respectively:

Sample function.json

{
    "scriptFile": "PreCompiledFunctionSample.dll",
    "entryPoint": "PreCompiledFunctionSample.MyFunction.Run",
    "bindings": [
        {
            "authLevel": "function",
            "name": "req",
            "type": "httpTrigger",
            "direction": "in"
        },
        {
            "name": "$return",
            "type": "http",
            "direction": "out"
        }
    ],
    "disabled": false
}

Sample function implementation

using System.Net;
using System.Linq;
using System.Threading.Tasks;
using System.Net.Http;

namespace PreCompiledFunctionSample
{
    public class MyFunction
    {
        public static async Task<HttpResponseMessage> Run(HttpRequestMessage req)
        {
            // parse query parameter
            string name = req.GetQueryNameValuePairs()
                .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
                .Value;

            // Get request body
            dynamic data = await req.Content.ReadAsAsync<object>();

            // Set name to query string or body data
            name = name ?? data?.name;

            return name == null
                ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
                : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
        }
    }
}

With this approach, functions can be developed as a regular class library, using any .NET language. For the above sample, the function folder contained the function.json and the assembly file, PreCompiledFunctionSample.dll

A sample project with the above function is available here