What is the purpose of AddSingleton method?

 Posted by Rajnilari2015 on 8/30/2016 | Category: ASP.NET Core Interview questions | Views: 648 | Points: 40
Answer:

The AddSingleton method, adds a singleton service of the type specified in TService with an implementation type specified in TImplementation to the specified Microsoft.Extensions.DependencyInjection.IServiceCollection. It returns a reference to this instance after the operation has completed.

The general syntax is

public static IServiceCollection AddSingleton<TService, TImplementation>(this IServiceCollection services)

where TService : class
where TImplementation : class, TService;

Services can be registered with the container in several ways.In this case we are using Singleton Service by using the AddSingleton<IService, Service>() method.Singleton lifetime services are created the first time they are requested and then every subsequent request will use the same instance. If the application requires singleton behavior, allowing the services container to manage the service's lifetime is recommended instead of implementing the singleton design pattern and managing the object's lifetime in the class.

e.g.

public void ConfigureServices(IServiceCollection services)

{
// Add framework services.
services.AddSingleton<IEmployeeRepository, EmployeeRepository>();
}


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response