如何在 C# Asp.net Core 中注入服務依賴項到控制器?


ASP.NET Core 透過建構函式或方法使用內建的 IoC 容器注入依賴類物件。

內建容器由 IServiceProvider 實現表示,預設支援建構函式注入。由內建 IoC 容器管理的型別(類)稱為服務。

為了讓 IoC 容器自動注入我們的應用程式服務,我們首先需要將它們註冊到 IoC 容器中。

示例

public interface ILog{
   void info(string str);
}
class MyConsoleLogger : ILog{
   public void info(string str){
      Console.WriteLine(str);
   }
}

ASP.NET Core 允許我們在 Startup 類的 ConfigureServices 方法中將應用程式服務註冊到 IoC 容器。ConfigureServices 方法包含一個 IServiceCollection 型別的引數,用於註冊應用程式服務。

如下所示,在 ConfigureServices() 方法中使用 IoC 容器註冊 ILog。

public class Startup{
   public void ConfigureServices(IServiceCollection services){
      services.AddSingleton<ILog, MyConsoleLogger>();
   }
}

IServiceCollection 例項的 Add() 方法用於向 IoC 容器註冊服務。

我們指定 ILog 為服務型別,MyConsoleLogger 為其例項。這將註冊 ILog 服務為單例。現在,IoC 容器將建立一個 MyConsoleLogger 類的單例物件,並在整個應用程式中將它注入到包含 ILog 作為建構函式或方法引數的類的建構函式中。

更新於:2020年9月25日

1K+ 瀏覽量

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.