Search code examples
.netdependenciesmaui

what is the difference between Dependency injection with builder.Services.Add vs DependencyService.Register?


What is the difference between

 var builder = MauiApp.CreateBuilder();
builder.Services.AddSingleton<ILocalize, Localize>();

vs

DependencyService.Register<ILocalize, Localize>();

Because when I want to resolve the ILocalize like below, first approach returns null, while Registering with 2nd one, it returns the instance. Are they using totally separate containers? I was expecting to register like the first approach always.

Will this work?

var localize = DependencyService.Get<ILocalize>();

Solution

  • .NET Multi-platform App UI (.NET MAUI) provides in-built support for using dependency injection. You may refer to the official doc: Dependency injection.

    For registration, just set it in MauiProgram.cs,

    builder.Services.AddTransient<ILocalize, Localize>();
    

    After a type is registered, it can be resolved or injected as a dependency. Two ways can be used to resolve it, Automatic dependency resolution and Explicit dependency resolution. Or you may use IServiceProvider Interface,

    readonly ILocalize _localizeService;
    
    public MainPageViewModel(IServiceProvider serviceProvider)
    {        
        _localizeService= serviceProvider.GetService<ILocalize>();
    }
    

    For more info, you may refer to Dependency injection, Maui Hybrid preload data before rendering first page.