问题
I know how to include other .csx
files via #load
. However, extension methods have to be defined in a top-level class, and #load
nests the class, so it's not top-level and the function throws a compilation error.
How do I use shared code without having it nest inside the function's post-compiled class?
回答1:
In order to correctly include extension methods for Azure Function you can use a #load as in all other cases, the only difference regarding the requirement that the extension methods needs to be in a top level class is to make them a top level methods :). When Azure Function gets compiled contents of csx files are being wrapped in a auto-created class, that's why it complains that extension methods written in a regular c# way will be nested inside of that auto-created class.
When that is understood there is a simple trick to have extension methods in separate csx file and still have them defined in top-level class:
here's run.csx file
#load "extensions.csx"
public static void Run(TimerInfo timer, TraceWriter log)
{
log.Info("test".MyToUpperExtension());
}
and extensions.csx
static string MyToUpperExtension(this string str)
{
return str.ToUpper();
}
static string MyToLowerExtension(this string str)
{
return str.ToLower();
}
As you see the only difference between regular extension methods is that you don't need to wrap them in a static class by yourself.
回答2:
One option you have is to create your extension method in a separate c# class and add it to your function.
From docs
If you need to reference a private assembly, you can upload the assembly file into a bin folder relative to your function and reference it by using the file name (e.g. #r "MyAssembly.dll"). For information on how to upload files to your function folder, see the following section on package management
.
来源:https://stackoverflow.com/questions/42285150/how-do-you-have-shared-extension-methods-in-azure-functions-without-nesting-clas