Using DI to encourage loose coupling

ASP.NET Core 3 includes a very simple built-in DI container, which supports constructor injection. To make a service available for the container, you have to add it within the ConfigureService method of the Startup class. Without knowing it, you have already done that before for MVC:

    public void ConfigureServices(IServiceCollection services) 
    { 
      services.AddControllersWithViews();
    } 

In fact, you have to do the same thing for your own custom services; you have to declare them within this method. This is really easy to do when you know what you are doing!

However, there are multiple ways of injecting your services and you need to choose which one best suits your needs:

  • Transient injection: Creates an instance every time the method is called (for example, stateless services):
        services.AddTransient<IExampleService, ExampleService>();
  • Scoped injection: Creates an instance once per request pipeline (for example, stateful services):
        services.AddScoped<IExampleService, ExampleService>(); 
  • Singleton injection: Creates one single instance for the whole application:
        services.AddSingleton<IExampleService, ExampleService>(); 
Note that you should add the instances for your services by yourself if you do not want the container to automatically dispose of them. The container will call the Dispose method of each service instance it creates by itself.

Here is an example of how to instantiate your services by yourself:
services.AddSingleton(new ExampleService());

Now that you understand how to use DI, let's apply your knowledge and create the next component for our sample application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.51.153