How to specify service lifetime for register service that added as a dependency C# Asp.net Core?


Built-in IoC container manages the lifetime of a registered service type. It automatically disposes a service instance based on the specified lifetime.

The built-in IoC container supports three kinds of lifetimes −

Singleton − IoC container will create and share a single instance of a service throughout the application's lifetime.

Transient − The IoC container will create a new instance of the specified service type every time you ask for it.

Scoped − IoC container will create an instance of the specified service type once per request and will be shared in a single request.

Example

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
   }
}

The following example shows the ways of registering types (service) using extension methods.

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));
   }
}

Updated on: 25-Sep-2020

453 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements