Marcel
Marcel

Reputation: 15742

How to use System.Runtime.Caching in an Azure Function App

I want to use simple in-memory caching of some values between function calls in a serverless function in an Azure Function App. I am developing directly in the Azure portal using C# script files. Following the suggestion 2) from this blog post by Mark Heath I have the following lines in my function's csx file:

#r "System.Runtime.Caching"
using System.Runtime.Caching;
using System;
static MemoryCache memoryCache = MemoryCache.Default;
//.....

This should be the System.Runtime.Caching assembly from this doc.

But on complilation (save in Azure Portal), I get:

2021-01-05T07:25:39.687 [Information] Script for function 'Intake' changed. Reloading.
2021-01-05T07:25:39.807 [Error] run.csx(1,1): error CS0006: Metadata file 'System.Runtime.Caching' could not be found
2021-01-05T07:25:39.865 [Error] run.csx(2,22): error CS0234: The type or namespace name 'Caching' does not exist in the namespace 'System.Runtime' (are you missing an assembly reference?)
2021-01-05T07:25:39.938 [Error] run.csx(4,8): error CS0246: The type or namespace name 'MemoryCache' could not be found (are you missing a using directive or an assembly reference?)
2021-01-05T07:25:40.008 [Error] run.csx(4,34): error CS0103: The name 'MemoryCache' does not exist in the current context
2021-01-05T07:25:40.041 [Information] Compilation failed.

This is my host.json, for reference:

{
  "version": "2.0",
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[1.*, 2.0.0)"
  }
}

Do I need to add something here? I would have expected, adding a #r reference to the assembly would be sufficient.

Upvotes: 1

Views: 1347

Answers (1)

Hari Subramaniam
Hari Subramaniam

Reputation: 1876

Upon inspecting the documentation, apart from the well-known assemblies mentioned in the document which can be referenced with #r, other nuget packages, may have to be uploaded by using a .proj file I suspect.

https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-csharp#using-nuget-packages

I crafted a function.proj file with its contents as follows

<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
    <PackageReference Include="System.Runtime.Caching" Version="5.0.0" />
</ItemGroup>

Then I uploaded function.proj using App Service Editor in the portal

Once that was complete, I was able to compile csx successfully

enter image description here

Upvotes: 1

Related Questions