Search code examples
azure-functionsazure-functions-core-tools

How do I import a Nuget package correctly for Azure Function v2?


I used Azure function core tools to make my function. I'm trying to import Newtonsoft.Json, but I can't get it to work correctly. Here is my basic setup:

function.proj:

<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>  
<ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="11.0.2"/>
</ItemGroup>

function.json:

{
  "disabled": false,
  "bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 * * * * *"
    }
  ]
}

run.csx:

using System;
using Newtonsoft.Json;

public static void Run(TimerInfo myTimer, ILogger log)
{
    log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}

host.json:

{
   "version":  "2.0"
}

When I run "func host start", it crashes immediately when it hits "using Newtonsoft.Json".

enter image description here

It appears to be monitoring my function.proj file correctly, because every time I save it, it claims that it is restoring my packages. enter image description here

Am I doing something wrong? How can I get my Nuget package?


Solution

  • In order to reference an external dependency in .csx files, you need to add #r <PackageName> (#r Newtonsoft.Json in this case) to the top of the file.

    Only certain dependencies are automatically referenced in Azure Functions, and select others are available without adding them to your project.json or function.proj file, as long as you reference them with the #r notation. For a more complete list, check out the C# developer reference for Azure Functions.