Maui dependency injection

Eduardo Gomez 3,426 Reputation points
2022-09-03T09:20:49.027+00:00

@Leon Lu (Shanghai Wicresoft Co,.Ltd.) I try to use the new dependency service in my app, but I broke it

Now is not calling the method to download the word.

Look

Maui Program

  public static MauiApp CreateMauiApp()  
    {  
        var builder = MauiApp.CreateBuilder();  
        builder.UseMauiApp<App>().ConfigureFonts(fonts =>  
        {  
            fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");  
            fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");  
        });  
  
        builder.Services.AddSingleton<WordService>();  
        builder.Services.AddSingleton<MainPageViewModel>();  
        builder.Services.AddSingleton<MainPage>();  
        builder.Services.AddSingleton<IGetWord, WordService>();  
        return builder.Build();  
    }  

IGetWord

public interface IGetWord  
{  
    Task<string> DownloadRandomWordAsync();  
}  

Serrvice, here is where I implemented the interface

public class WordService : IGetWord  
{  
    readonly HttpClient client;  
  
    public WordService()  
    {  
        client = new HttpClient();  
    }  
  
    public async Task<string> DownloadRandomWordAsync()  
    {  
        var url = "https://random-words-api.vercel.app/word/";  
  
        var response = await client.GetAsync(url);  
  
        if (response.IsSuccessStatusCode)  
        {  
            var json = await response.Content.ReadFromJsonAsync<List<WordClass>>();  
  
            return json.FirstOrDefault().word;  
        }  
  
        return null;  
    }  
}  

And Finally my VM

public partial class MainPageViewModel : ObservableObject  
{  
    readonly IGetWord getWord;  
  
    string answer = string.Empty;  
    readonly List<char> charList = new();  
  
    [ObservableProperty]  
    private string _spotlight;  
  
  
    public MainPageViewModel(IGetWord getWord)  
    {  
        this.getWord = getWord;  
    }  
  
    private async Task<string> GetWord()  
    {  
        answer = await getWord.DownloadRandomWordAsync();  
        return answer;  
    }  
  
    private void CalculateWord(string ans, List<char> guessed)  
    {  
        var temp = ans.Select(x => guessed.IndexOf(x) >= 0 ? x : '_').ToArray();  
        Spotlight = string.Join(' ', temp);  
    }  
  
    public async Task InitializeAsync()  
    {  
        answer = await GetWord();  
        CalculateWord(answer, charList);  
    }  
  
}  
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,542 questions
0 comments No comments
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 76,001 Reputation points Microsoft Vendor
    2022-09-07T09:24:13.063+00:00

    Hello,

    I tried o call it it the constructor, but my app frezes

    You cannot call await/async method in the constructor
    You can refer to The Asynchronous Initialization Pattern.

    1. Create a IAsyncInitialization interface public interface IAsyncInitialization
      {
      Task InitializeAsync();
      }
      1. Then implement this interface and initialize this InitializeAsync() in your MainPageViewModel constructor(Note: do not forget to add public Task Initialization { get; private set; }). public partial class MainPageViewModel : ObservableObject, IAsyncInitialization
        {
        readonly IGetWord getWord;
        string answer = string.Empty;
        // I add characters for tesing.
        readonly List<char> charList = new() { 'j', 'a', 'c' }; [ObservableProperty]
        private string _spotlight; public MainPageViewModel(IGetWord getWord)
        {
        this.getWord = getWord;
        //initialize this InitializeAsync()
        Initialization = InitializeAsync(); }
        public Task Initialization { get; private set; } private void CalculateWord(string ans, List<char> guessed)
        {
        var temp = ans.Select(x => guessed.IndexOf(x) >= 0 ? x : '_').ToArray();
        Spotlight = string.Join(' ', temp);
        }
        private async Task<string> GetWord()
        {
        answer = await getWord.DownloadRandomWordAsync();
        return answer;
        }
        public async Task InitializeAsync()
        {
        answer = await GetWord();
        CalculateWord(answer, charList);
        }
        }

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. John Hair 371 Reputation points
    2022-09-03T19:46:24.027+00:00

    Is InitializeAsync being called anywhere?


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.