Dependency Injection
Important
This project is an experimental release. We hope you try out Experimental Mobile Blazor Bindings and provide feedback at https://github.com/xamarin/MobileBlazorBindings.
Incorporating dependency injection into an application involves a few steps:
Defining an interface of class for the service. The weather app sample foregoes interface definitions due to the simple nature of the app, but would otherwise have an interface named
IWeatherService
with methods on it such asWeatherReport GetWeatherReport()
.Implementing the service interface with a concrete implementation. For example:
public class WeatherService : IWeatherService { public WeatherReport GetWeatherReport() { // Get weather report data... return weatherReport; } }
Registering the service with the host in
App.cs
's constructor:var host = Host.CreateDefaultBuilder() .ConfigureServices((hostContext, services) => { // Register app-specific services services.AddSingleton<IWeatherService, WeatherService>(); }) .Build();
Several registration methods for services are available on the
ServiceCollectionServiceExtensions
class.Consuming the services. There are several ways to consume the services, and two of the most popular ways are:
Constructor injection in custom types also registered in the dependency injection container. To consume a service in this way, add a constructor parameter to your class that uses the service, and when that class is retrieved from the DI container, it will have its parameters populated with other services from the DI container.
Consuming services in
.razor
files is done with the@inject
directive, which is used in theMainPage.razor
file:@inject WeatherService WeatherService
Learn more about the
@inject
directive in the Blazor documentation.
Tip
In hybrid apps, services are shared between the native UI of the app, the web part of the app, and everywhere else. There are no special steps required to share services and state between areas of hybrid apps.