Dependency Injection Constructor doesn't sees object

Viewed 50

In fresh MAUI.NET I have registered the singletons in MauiProgram.cs

builder.Services.AddSingleton<InformationView>();
builder.Services.AddSingleton<InformationViewModel>();

I have public empty class InformationViewModel and I have default ContentView (XAML) item with the .cs part content like this:

    public InformationViewModel viewModel;
    public InformationView(InformationViewModel viewModel)
    {
        InitializeComponent();
        viewModel = viewModel;
    }

in MainPage.cs I try to get my registered singletons like that:

    public MainPage()
    {
        InitializeComponent();
        InformationView view = new InformationView(InformationViewModel informationViewModel);
    }

I have look for a MonkeyFinder sample application provided by Microsoft and its training by Gerald Versluis. It seems that MonkeyService is done in same way and is working while I get this errors in the above line of MainPage.cs:

Error CS1729 'InformationView' does not contain a constructor that takes 2 arguments Error CS1003 Syntax error, ',' expected
Error CS0119 'InformationViewModel' is a type, which is not valid in the given context
Error CS0103 The name 'informationViewModel' does not exist in the current context

What should I do to fix it?

Edit

Following seems to be working and "singleton" properties are handled - I got always the same instance whenever I call it.

InformationViewModel informationViewModel = new InformationViewModel();
InformationView view = new InformationView(informationViewModel);

Edit 2 It wasn't obvious for me, that you need to trigger "the first object in hierarchy of construction" by DI and this would happen. I was expecting that if I create a "new instance" it would not "fire" the whole DI for internal dependencies. So MauiWinUIApplication.Current.Services.GetService<InformationView>(); would do all DI I was expecting.

0 Answers
Related