﻿# 如何讓 Azure Functions 也可以支援 dotnet watch 自動監視程式變更重啟

在用 .NET Core 3.1 開發 Azure Functions 的時候一直以來有個困擾，那就是每次改完程式都要回到 Terminal 中斷程式執行，並且重新啟動，沒有像其他應用程式那樣可以用 `dotnet watch run` 自動監視檔案變更就自動重啟應用程式。雖然這個功能沒有內建在 `func start` 命令中，但是我卻發現 .NET CLI 竟然有個 `dotnet watch msbuild` 可以用，雖然陽春了點，但其實也是還是可以滿足需求！ 👍

### 建立 Azure Functions 應用程式

1.  安裝 [Azure CLI](https://learn.microsoft.com/zh-tw/cli/azure/install-azure-cli?WT.mc_id=DT-MVP-4015686) 與 [Azure Functions Core Tools 3.x](https://learn.microsoft.com/zh-tw/azure/azure-functions/functions-run-local?WT.mc_id=DT-MVP-4015686) 工具
    
    ```bash
    choco install azure-cli azure-functions-core-tools-3 azure-cli -y
    ```
    
2.  建立 [Azure Functions](https://azure.microsoft.com/zh-tw/services/functions/?WT.mc_id=DT-MVP-4015686) 應用程式
    
    ```bash
    func init MyFunc --worker-runtime dotnet
    cd MyFunc
    ```
    
3.  建立 Function 函式
    
    ```bash
    func templates list -l
    func templates list -l C#
    
    func new --template "Http trigger" --name Funcion1
    ```
    
4.  啟動 Azure Functions 應用程式
    
    ```bash
    func start
    ```
    
5.  測試 API 連線
    
    ```
    http://localhost:7071/api/Funcion1?name=Will
    ```
    

### 設定程式碼變更就自動重新啟動

1.  開啟 `MyFunc.csproj` 專案檔
    
    請加入以下自訂的 `RunFunctions` 目標：
    
    ```xml
    <Target Name="RunFunctions">
        <Exec Command="func start --verbose=false" />
    </Target>
    ```
    
2.  使用 `dotnet watch msbuild` 建置並執行目標
    
    這裡透過 `/t:RunFunctions` 明確指定要執行 MSBuild 中的 `RunFunctions` 目標(Target)，啟動之後就會自動監視資料夾中的 `*.cs` 檔案變更，有變更就會自動重新啟動 `func start` 執行！
    
    ```bash
    dotnet watch msbuild /t:RunFunctions
    ```
    
    > 由於這招是透過 `dotnet watch msbuild` 先建置專案，之後再透過 `func start` 啟動專案，而 `func start` 本身就包含了 MSBuild 命令，所以等於會建置兩次，因此速度稍微慢一點。雖然有 `func start --no-build` 參數可以避免重複建置，但是這個命令會在啟動時找不到 Function 可用，這個問題我已經回報 [No job functions found if run "func start --no-build" #2705](https://github.com/Azure/azure-functions-core-tools/issues/2705) 列管中，持續追蹤！
    

### 相關連結

-   [Hot reload · Issue #1239 · Azure/azure-functions-core-tools](https://github.com/Azure/azure-functions-core-tools/issues/1239#issuecomment-669018902)
-   [Develop ASP.NET Core apps using a file watcher | Microsoft Docs](https://learn.microsoft.com/en-us/aspnet/core/tutorials/dotnet-watch?view=aspnetcore-5.0&WT.mc_id=DT-MVP-4015686#custom-watch-projects)
-   [如何安裝 Azure CLI | Microsoft Docs](https://learn.microsoft.com/zh-tw/cli/azure/install-azure-cli?WT.mc_id=DT-MVP-4015686)
-   [使用 Azure Functions Core Tools | Microsoft Docs](https://learn.microsoft.com/zh-tw/azure/azure-functions/functions-run-local?WT.mc_id=DT-MVP-4015686)
