如何為新增到依賴項中的註冊服務指定服務生命週期 C# Asp.net Core?


內建 IoC 容器管理已註冊服務型別的生命週期。它基於指定生命週期自動處理服務例項。

內建 IoC 容器支援三種生命週期−

單例 − IoC 容器將建立並共享整個應用程式生命週期中服務的單個例項。

瞬態 − IoC 容器每次在請求指定服務型別時,都將建立一個新例項。

作用域 − IoC 容器每個請求建立一個指定服務型別的例項,並在單個請求中共享。

示例

public interface ILog{
   void info(string str);
}
class MyConsoleLogger : ILog{
   public void info(string str){
      Console.WriteLine(str);
   }
}
public class Startup{
   public void ConfigureServices(IServiceCollection services){
      services.Add(new ServiceDescriptor(typeof(ILog), new
      MyConsoleLogger())); // singleton
      services.Add(new ServiceDescriptor(typeof(ILog),
      typeof(MyConsoleLogger), ServiceLifetime.Transient)); // Transient
      services.Add(new ServiceDescriptor(typeof(ILog),
      typeof(MyConsoleLogger), ServiceLifetime.Scoped)); // Scoped
   }
}

以下示例演示了使用擴充套件方法註冊型別(服務)的方法。

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

更新於:2020-9-25

555 人閱讀

開啟你的 職業 生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.