練習 - 登錄及取用服務

已完成

ASP.NET Core 應用程式通常需要跨多個元件存取相同的服務。 ASP.NET Core 會使用內建的相依性插入容器來管理應用程式所使用的服務。

小組負責人請您建立公司的裸機網站。 網站應該會在主頁面上顯示歡迎訊息。 您決定建立服務來產生歡迎訊息。 接著,您會向服務容器登錄服務,以便將其插入需要它的元件中。

建立 ASP.NET Core 應用程式

您需要 ASP.NET Core 應用程式來扮演小組應用程式的角色。 讓我們在 Visual Studio Code 中使用 C# 開發套件延伸模組建立新的 ASP.NET Core 應用程式。

  1. 啟動 Visual Studio Code。

  2. Ctrl+Shift+P 以開啟命令選擇區。

  3. 搜尋並選取 [.NET:新增專案...]。

  4. 搜尋並選取 [ASP.NET Core Empty]

    已選取 [ASP.NET Core Empty] 之命令選擇區的螢幕擷取畫面。

  5. 選取或建立新專案的資料夾。

  6. 將新的應用程式命名為「MyWebApp」

  7. 選取 [建立專案] 以建立專案。

  8. 當新專案開啟時,展開 [Solution Explorer] 窗格以檢視專案檔。

    Visual Studio Code 中 [方案總管] 窗格的螢幕快照。

執行應用程式

測試應用程式以確定其可執行。

  1. 在 Visual Studio Code 中,按 F5 建置並執行應用程式。

    1. 出現提示時,選取 [C#] 作為偵錯工具。
    2. 出現提示時,選取 [C#: MyWebApp [預設設定]] 作為要使用的啟動設定。

    此命令會啟動應用程式,並將其裝載在本機網頁伺服器上。 瀏覽器視窗隨即開啟並顯示「Hello, World!」

  2. 在 Visual Studio Code 中按 Shift+F5 以關閉瀏覽器視窗並停止應用程式。

建立服務

既然您已有運作中的應用程式,讓我們建立一個服務,為主頁面產生歡迎訊息。

  1. Explorer 窗格中,以滑鼠右鍵點擊 MyWebApp 專案。 選取 [新增資料夾]。 將資料夾命名為 Services

  2. 以滑鼠右鍵按一下 [服務] 資料夾。 選取 [新增檔案]。 將檔案命名 WelcomeService.cs

  3. 使用下列程式代碼取代 WelcomeService.cs 的內容:

    namespace MyWebApp.Services;
    
    public class WelcomeService : IWelcomeService
    {
    
        DateTime _serviceCreated;
        Guid _serviceId;
    
        public WelcomeService()
        {
            _serviceCreated = DateTime.Now;
            _serviceId = Guid.NewGuid();                
        }
    
        public string GetWelcomeMessage()
        {
            return $"Welcome to Contoso! The current time is {_serviceCreated}. This service instance has an ID of {_serviceId}";
        }
    }
    

    此程式碼會使用產生歡迎訊息的 GetWelcomeMessage 方法,定義 WelcomeService 類別。 該訊息包含服務建立時的目前時間,以及服務的每個執行個體的唯一識別碼。

    請注意,建構函式中會設定 _serviceCreated_serviceId 欄位,而且其在服務執行個體的存留期一律不會變更。

註冊服務

既然您有服務,您必須向服務容器登錄它。

  1. 開啟 Program.cs 檔案。

  2. 將下列指示詞新增至檔案的頂端:

    using MyWebApp.Services;
    

    這個指示詞會解析 WelcomeService 類別的參考。

  3. 緊接在 var builder = WebApplication.CreateBuilder(args); 行之後,新增下列程式碼:

    builder.Services.AddSingleton<WelcomeService>();
    

    WebApplication.CreateBuilder 會建立 WebApplicationBuilder 類別的新執行個體,稱為 builder。 上述程式碼會向具有單一存留期的服務容器登錄 WelcomeService 類別。

  4. app.MapGet("/", () => "Hello World!"); 行變更為下列程式碼:

    app.MapGet("/", (WelcomeService welcomeService) => welcomeService.GetWelcomeMessage());
    

    此程式碼會將 HTTP GET 要求對應至根 URL (/) 至委派,以傳回 WelcomeService 服務所產生的歡迎訊息。

    您的 Program.cs 檔案看起來應該像這樣:

    using MyWebApp.Services;
    
    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddSingleton<WelcomeService>();
    
    var app = builder.Build();
    
    app.MapGet("/", (WelcomeService welcomeService) => welcomeService.GetWelcomeMessage());
    
    app.Run();
    

測試變更

  1. 儲存所有變更,並和之前一樣地執行應用程式。
  2. 當瀏覽器視窗開啟時,請注意根 URL 會顯示 WelcomeService 服務所產生的歡迎訊息。
  3. 在 Visual Studio Code 中按 Shift+F5 以關閉瀏覽器視窗並停止應用程式。

使用介面

您的小組會檢閱您的程式碼,而另一位開發人員會建議您使用介面來登錄服務,因為這種方法可讓程式碼更有彈性且更容易維護。

  1. Explorer 窗格中,以滑鼠右鍵點擊 MyWebApp 專案。 選取 [新增資料夾]。 將該資料夾命名為 [介面]

  2. 以滑鼠右鍵按一下 [介面] 資料夾。 選取 [新增檔案]。 將檔案命名 IWelcomeService.cs

  3. 使用下列程式代碼取代 IWelcomeService.cs 的內容:

    namespace MyWebApp.Interfaces
    
    public interface IWelcomeService
    {
        string GetWelcomeMessage();
    }
    

    此程式碼會使用 GetWelcomeMessage 方法定義 IWelcomeService 介面。 任何實作此介面的服務都必須提供 GetWelcomeMessage 方法的實作。

  4. 開啟 Services/WelcomeService.cs 檔案。

  5. 將下列指示詞新增至檔案的頂端:

    using MyWebApp.Interfaces;
    

    這個指示詞會解析您在下一個步驟中新增之 IWelcomeService 介面的參考。

  6. 更新 WelcomeService 類別宣告以實作 IWelcomeService 介面:

    public class WelcomeService : IWelcomeService
    

    這是您唯一需要對 WelcomeService 類別進行的變更,以實作 IWelcomeService 介面。 WelcomeService 類別已經有 GetWelcomeMessage 方法,其符合 IWelcomeService 介面中的方法簽章。

  7. 開啟 Program.cs 檔案。

  8. builder.Services.AddSingleton<WelcomeService>(); 行更新為下列程式碼:

    builder.Services.AddSingleton<IWelcomeService, WelcomeService>();
    

    此程式碼會使用 IWelcomeService 介面向服務容器登錄 WelcomeService 類別。

    提示

    將此想成說出「當元件要求 IWelcomeService 時,請提供 WelcomeService 的執行個體。」

  9. app.MapGet("/", (WelcomeService welcomeService) => welcomeService.GetWelcomeMessage()); 行更新為下列程式碼:

    app.MapGet("/", (IWelcomeService welcomeService) => welcomeService.GetWelcomeMessage());
    

    匿名函式現在預期 IWelcomeService,而不是 WelcomeService

    您的 Program.cs 檔案看起來應該像這樣:

    using MyWebApp.Interfaces;
    using MyWebApp.Services;
    
    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddSingleton<IWelcomeService, WelcomeService>();
    
    var app = builder.Build();
    
    app.MapGet("/", (IWelcomeService welcomeService) => welcomeService.GetWelcomeMessage());
    
    app.Run();
    

測試變更

讓我們測試應用程式,以確定它仍如預期般運作。

  1. 儲存所有變更,並和之前一樣地執行應用程式。
  2. 當瀏覽器視窗開啟時,請注意根 URL 會顯示 WelcomeService 服務所產生的歡迎訊息。
  3. 讓應用程式保持執行以便進行下一個練習。