Sunday, September 2, 2018

.Net Core | Dependency Injection (DI/Ioc)

Dependency Injection(DI) & Inversion of Control(Ioc)
  • ConfigureServices is the method used to register Types/ Services in Ioc container.
  • Classes of application (even view using Razor) can call these services whenever required.
  • If a class uses any Ioc registered service instance, its required to implement interface of that service in the class.
  • Lifetime of registered service instances is managed by runtime(framework). Because you already mention the same while registering a service.

Ex.

public void ConfigureServices(IServiceCollection services)  
{  
        services.AddSingleton<IEmailSender, EmailSender>();
        services.AddMvc();  
services.AddSingleton<InterfaceName, className>();
services.AddScoped<InterfaceName, className>();
services.AddTransient<InterfaceName, className>();


Benefits: 
  • Required services instance can be used throughout the application.
  • No need to create and dispose services instances when calling them.
  • Lifetime of services instances managed by Ioc container, that is called by runtime.

No comments:

Post a Comment

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...