Learn
Dependency Injection
Review
Whew! You made it through a lot of content. Let’s review:
- Dependencies in our code can cause problems, like:
- The codebase is harder to maintain
- We can’t test classes individually
- The system isn’t flexible enough to allow us to swap the dependency for something similar
- The Dependency Inversion Principle (DIP) attempts to resolve theses dependency problems by the use of abstraction:
- “High-level modules should not depend on low-level modules. Both should depend on abstractions (e.g. interfaces).”
- “Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.”
- Inversion of Control (IoC) is a programming principle that attempts to resolve the dependency problems by giving control to the framework, rather than the dependent class:
- “Methods defined by the user should be called from within the framework itself, rather than from the user’s application code”
- To apply these principles in our code, we use interfaces and dependency injection
- There are many ways to inject but we used constructor injection
- To do all of this in ASP.NET, we can use the provided IoC container
- We register services with the container by adding “AddX” methods to
Startup.ConfigureServices()
- We can register built-in services, like database context, with built-in methods, like:public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddDbContext<SomeContext>(); }
- We can access some default-registered services, like
ILogger<T>
, without registering additional services - We can register custom services, with “AddX” methods, likepublic void ConfigureServices(IServiceProvider services) { services.AddScoped<IAccount, CustomerAccount>(); services.AddTransient<IResponder, Responder>(); services.AddSingleton<ILogger, Logger>(); }
Sometimes programming principles can feel hard to grasp without actual examples. We provided some in this lesson, but you can find more in these sources:
Instructions
Well done! The ASP.NET example code is provided here if you’d like to review it.