Azure Functions - Shared classes

2019-02-06 08:27发布

问题:

I want to use some shared classes on my Azure Functions to not duplicate code.

I have tried to create a empty C# function and create the classes inside the function and then import to the other functions with:

#r "../Shared/Class.cs"

回答1:

First, put your shared code inside a folder in the root of your Function App directory (e.g. "Shared"). Let's say I put a shared Message.csx class in that folder (e.g. full path D:\home\site\wwwroot\Shared\Message.csx).

To include this into your function use the #load command:

#load "..\Shared\Message.csx"

using System;
using Microsoft.Azure.WebJobs.Host;

public static void Run(Message message, TraceWriter log)
{
    log.Info($"C# Queue trigger function processed message: {message.Id}");
}

See the help page here for more information. By default, the files in that directory won't be tracked for changes. If you want to ensure that when files in that directory change your functions will pick up the changes and be recompiled, you can add your "Shared" directory to the watchDirectories list in host.json. E.g.:

{
    "watchDirectories": [ "Shared" ]
}


回答2:

Due to the rate of change within Azure Functions, this is no longer the recommended approach for C# functions( see Azure Functions Tools Roadmap). Refer to the following blog posts for depictions of the most modern and efficient patterns for structure a C# project in visual studio, and get all the advantages of shared DLL's the way you normally do in C#.

https://blogs.msdn.microsoft.com/appserviceteam/2017/03/16/publishing-a-net-class-library-as-a-function-app/

https://github.com/devkimchi/Precompiled-Azure-Functions-Revisited



回答3:

When working from Visual Studio and looking for a way to share some C# script files between functions within your Function App like this:

#load "..\Shared\MySharedCode.csx"

Please be aware that you should set the 'Copy to Output Directory' property foor the files in your shared folder to 'Copy always'.