Introducing DI
When I first learned how to do DI in code, I had a euphoria as if I had discovered a secret in software engineering; it is like code magic. We have been exploring dependencies in the previous sections and now, we are about to discover injecting these dependencies into our classes. The next step is explaining what DI is and using practical samples from the WFA application to make sure you are experimenting with a variety of scenarios. The best way to introduce DI is with a familiar example.
First example of DI
DI is all over any modern .NET code. In fact, we have one example right here in the ASP.NET template code:
public WeatherForecastController( ILogger<WeatherForecastController> logger) { _logger = logger;
The logger
object, which is a dependency, is injected into the controller when a new instance of the controller is created. There is nowhere in the controller that we are instantiating the logger...