3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Azure Functions 開発の初歩(.NET 8 / Isolated Worker)

3
Posted at

Azure Functions 開発の初歩(.NET 8 / Isolated Worker)

1. 使用バージョン

本ガイドでは以下のバージョンを使用します。

ツール バージョン
.NET SDK 8.0.420
Azure Functions Core Tools v4 4.0.5455

2. 事前確認(インストール済みか確認)

インストールされているか確認します。
バージョン確認のコマンドを実行して対象のバージョンが表示されればインストール済です。
インストール済の場合はインストールの手順は不要です。

.NET 8 SDK

dotnet --list-sdks

出力例

8.0.420 [C:\Program Files\dotnet\sdk]

Azure Functions Core Tools v4

func --version

出力例

4.0.5455

3. インストール手順

インストールされていないツールがある場合はインストールします。

.NET 8 SDK を Windows にインストールする

  • SDK を選択(Runtime ではない)
  • Windows x64 を選択
  • インストール後は PowerShell を再起動

使用したインストーラー

  • dotnet-sdk-8.0.420-win-x64.exe

Azure Functions Core Tools v4 のインストール

使用したインストーラー

  • func-cli-4.0.5455-x64.msi

4. プロジェクト作成(.NET Isolated Worker)

4-1. VSCode 自動生成バグ回避

VSCode の .vscode 自動生成バグ回避のため

setx FUNCTIONS_CORE_TOOLS_SKIP_VSCODE "true"

4-2. プロジェクト初期化

func init . --worker-runtime dotnet-isolated

成果物

C:.
│  .gitignore
│  host.json
│  local.settings.json
│  Program.cs
│  tmp.csproj
│
├─.vscode
│      extensions.json
│
└─Properties
        launchSettings.json

4-3. Function 作成

func new --name Hello --template "HTTP trigger"

実行結果

Template: HTTP trigger
Function name: Hello
Creating dotnet function...
The function "Hello" was created successfully from the "HTTP trigger" template.

作成後の構造

.
│  .gitignore
│  Hello.cs
│  host.json
│  local.settings.json
│  Program.cs
│  sample.csproj
│
├─.vscode
│      extensions.json
│
├─obj
│      project.assets.json
│      project.nuget.cache
│      sample.csproj.nuget.dgspec.json
│      sample.csproj.nuget.g.props
│      sample.csproj.nuget.g.targets
│
└─Properties
        launchSettings.json

4-4 .NET 8 に変更

sample.csprojを開いて編集する。
バージョンが6.0になっている場合は8.0に修正する。

<TargetFramework>net6.0</TargetFramework>

↓↓↓

<TargetFramework>net8.0</TargetFramework>

4-5 ビルド

dotnet build

5. VSCode拡張機能

VSCodeで編集する場合は以下の拡張機能のインストールを推奨

  • Azure Functions
  • C# Dev Kit

6. ロジックと Function の分離(テストしやすい構成)

sampleプロジェクトの構成変更

今回のテストはHttpリクエスト部分ではなくロジック部分のみテストするため、
ロジック部分をServices配下のクラスにします。

.
│
├─Functions
│      Hello.cs
│
└─Services
        HelloService.cs

HelloService.cs

namespace sample.Services;

public class HelloService
{
    public string GetMessage()
    {
        return "Hello Azure Functions!";
    }
}

Hello.cs

using System.Net;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using sample.Services;

namespace sample.Functions;

public class Hello
{
    private readonly HelloService _service;

    public Hello(HelloService service)
    {
        _service = service;
    }

    [Function("Hello")]
    public HttpResponseData Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req)
    {
        var message = _service.GetMessage();

        var response = req.CreateResponse(HttpStatusCode.OK);
        response.WriteString(message);
        return response;
    }
}

Program.cs

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using sample.Services;

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureServices(services =>
    {
        // HelloService を DI コンテナに登録
        services.AddSingleton<HelloService>();
    })
    .Build();

host.Run();

7. 動作確認

7-1. ローカルサーバーの起動

プロジェクトのルートディレクトリで以下のコマンドを実行します。

func start

起動に成功するとエンドポイントが表示されます。

Functions:

        Hello: [GET,POST] http://localhost:7071/api/Hello

7-2. エンドポイントへのリクエスト送信

サーバーを起動した状態で、別のターミナルを開いて curl コマンドでリクエストを送信します。

curl http://localhost:7071/api/Hello

以下のように応答が返ってくれば成功です。

Hello Azure Functions!

ブラウザから直接URLにアクセスしても同じ結果を確認できます。

8. ユニットテスト (xUnit)

8-1. テストプロジェクト作成

ユニットテストのテンプレートを作成する。

dotnet new xunit -n sample.Tests

成功すると

テンプレート "xUnit Test Project" が正常に作成されました。
正常に復元されました。

といったメッセージが出力されます。

8-2. 本体プロジェクトを参照追加

cd .\sample.Tests\
dotnet add reference ../sample/sample.csproj

実行結果

参照 `..\sample\sample.csproj` がプロジェクトに追加されました。

8-3. テスト構成

.
  sample.Tests.csproj
  sample.Tests.sln
└─Services
        HelloServiceTests.cs

8-4 テストコード

using sample.Services;
using Xunit;

public class HelloServiceTests
{
    [Fact]
    public void GetMessage_ReturnsExpectedMessage()
    {
        var service = new HelloService();
        var result = service.GetMessage();

        Assert.Equal("Hello Azure Functions!", result);
    }
}

9. テスト実行

sample.Tests.csproj
のあるフォルダに移動し、 dotnet test コマンドを実行

dotnet test

以下が実行されます。

  1. sample(本体)をビルド
  2. sample.Tests(テスト)をビルド
  3. sample.dll を読み込んでテスト実行
  4. 結果を表示

実行結果の例

成功!   -失敗:     0、合格:     1、スキップ:     0、合計:     1、期間: < 1 ms - sample.Tests.dll (net8.0)

合格が1件でテスト成功です。

以上です。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?