Constructor injection

We have just seen how we can initialize services in our Startup class, but how can we consume these services? By default, the built-in dependency injection container of ASP.NET Core uses the constructor injection pattern to retrieve services. We can modify ValueController to use IPaymentServices by adding the interface as a parameter of the controller constructor:

using Microsoft.AspNetCore.Mvc;

namespace SampleAPI.Controllers
{
[ApiController]
[Route("[controller]")]
public class ValuesController : ControllerBase
{
private IPaymentService paymentService { get; set; }

public ValuesController(IPaymentService paymentService)
{
this.paymentService = paymentService;
}

public string Get()
{
return paymentService.GetMessage();
}
}
}

As you can see, we can inject the IPaymentService interface into the constructor of our class. It should be noted that to be compliant with constructor injection, the constructor has to abide by the following rules:

  • The constructor should be public: If our constructor is not public, the reflection process cannot access the constructor.
  • There should be only one applicable constructor: For example, if we declare multiple constructors in our ValuesController class, such as public ValuesController(IPaymentService paymentService) or public ValuesController(IPaymentService paymentService, string[] paymentTypes = new string[] { 1, 2, 3 }), the runtime would throw InvalidOperationException. There should be only one constructor that is suitable for dependency injection.
  • You can only pass arguments that are not provided by dependency injection if they have a default value. For example, the following constructor is suitable for constructor injection: public ValuesController(IPaymentService paymentService, string[] paymentTypes = new string[] { 1, 2, 3 }).

The resolution of the dependencies happens during the runtime execution; therefore, we need to adhere to these rules in order to avoid pitfalls when we alter the dependencies of a controller class. 

In conclusion, dependency injection provides a smart way to resolve the dependencies of classes. You should also try to be compliant with the Single Responsibility Principle (SRP). The SRP states that a class should have responsibility for a single part of the functionality. Classes with a lot of injected dependencies are probably not compliant with the SRP. Avoiding these kinds of bad design practices improves the maintainability of our code, and avoids our classes being tightly coupled with static functionalities, which prevent them from being testable. Let's proceed with the next section that covers the action method injection technique.

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

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