2

MAUI has dependency injection setup similar to what ASP.NET Core has in the Startup.cs class. This one is set in MauiProgram.cs file by default.

My question is: How can I get a service instance in this file after services registration? I guess, one solution will be the following, but then I must edit this code also if the constrctors of these services change during time:

    var keyValueStore = new PreferencesKeyValueStore();
    var accountService = new AccountService(keyValueStore);
    var profileService = new ProfileService(keyValueStore);
    
    builder.Services.AddSingleton<IKeyValueStore>(keyValueStore);
    builder.Services.AddSingleton<IAccountService>(accountService);
    builder.Services.AddSingleton<IProfileService>(profileService);

    //Here now I can use accountService and profileService to do something

I can not find more elegant solution that will return the service instance for me from the DI container. Something like:

    builder.Services.AddSingleton<IKeyValueStore, PreferencesKeyValueStore>();
    builder.Services.AddSingleton<IAccountService, AccountService>;
    builder.Services.AddSingleton<IProfileService, ProfileService>();
    
    //Now I can't perform something like: var accountService = diContainer.GetInstance<IAccountService>(); or similar.

I don't know how to reach di container and ask it to provide me registered instance.

Cfun
  • 8,442
  • 4
  • 30
  • 62
Miloš
  • 149
  • 1
  • 12

1 Answers1

3

Actually, the documentation provided a simple way to do so. Check it here

They recommended to use the Handler property of any object of type Element, there you can write the code :

// Considering you want to resolve a service from your custom interface IMyService

var service = this.Handler.MauiContext.Services.GetService<IMyService>();

// Then you can use the resolved service..

But there are some issues, personally it never worked for me, the Handler property may be null because of the lifecycle of the Element you are calling it on.

To avoid this issue, use a full line like:

var service = Application.Current.MainPage
    .Handler
    .MauiContext
    .Services
    .GetService<IMyService>();

// Then you can use the resolved service..

This works fine for me Hope it helps you ..

Djoufson
  • 31
  • 6