Here you will learn how Dependency Injection can be leveraged in Blazor

Most apps today are dependent on remote or built-in services. With Blazor, we can use dependency injection to register custom services and make them available throughout the app, just like we would do with any C# application.

About Dependency Injection (DI)

In Short, dependency injection is a technique which delivers a key advantage, “loose coupling”. With DI, objects that have dependencies, don’t need to resolve them, rather the dependencies are resolved for them by injecting them into the object when they are created.

DI in Blazor

In Blazor, Components that use Dependency Injection (DI) are not coupled to a concrete type, they are bound to an Interface, this way, we can even test, mock and/or test the implementation, simply by swapping it when writing unit tests against it. DI on blazor is based on .NET’s System.IServiceProvider which basically is a generic mechanism of retrieving services in .NET

Adding Services to the DI

Just like any normal .NET Core app, we will setup our DI in the Startup.cs file, inside the method Startup.ConfigureServices .

To Demonstrate DI we will create a little to-do app that will display and add todos, displaying them in the page.