Share via

dependecy injection

Eduardo Gomez Romero 1,375 Reputation points
2024-11-11T11:43:53.35+00:00

For some reason, I am getting a cast error when registering a view Model and I don't know what is going on

https://reccloud.com/u/44yiurs

 public static MauiApp CreateMauiApp() {
        var builder = MauiApp.CreateBuilder();
        builder
            .UseMauiApp<App>()
            .UseMauiCommunityToolkit()
            .ConfigureFonts(fonts => {
                fonts.AddFont("MaterialIcons-Regular.ttf", "MaterialSymbol");
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
            }).ConfigureMauiHandlers(handlers => {

                handlers.AddHandler<BorderlessEntry, EntryHandler>();
            });

        BorderlessEntryHandler.ApplyCustomHandler();

        builder.Services.AddSingleton<AppShell>();

        builder.Services.AddSingleton<LoginPage, LoginViewModel>();

        builder.Services.AddSingleton<MainPage, MainViewModel>();

        return builder.Build();
    }
}


Login Page view Model

public partial class LoginPageViewModel : ObservableObject {

    [RelayCommand]
    void ChangeVisibility() { }
}

public partial class LoginPage : ContentPage {
    public LoginPage(LoginPageViewModel loginView) {
        InitializeComponent();
        BindingContext = loginView;
    }

}

System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'

Net8

Windows, Android

Developer technologies | .NET | .NET Multi-platform App UI
0 comments No comments

Answer accepted by question author

Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 50,166 Reputation points Microsoft External Staff
2024-11-12T01:46:31.5966667+00:00

Hello,

This issue is caused by incorrect usage of the AddSingleton method.

If you pass in two parameters builder.Services.AddSingleton<MainPage, MainViewModel>(); when using this method, according to the description in the ServiceCollectionServiceExtensions.AddSingleton Method, you need to pass in a Service interface and its implementation class.

AddSingleton<TService,TImplementation>(IServiceCollection): Adds a singleton service of the type specified in TService with an implementation type specified in TImplementation to the specified IServiceCollection.

For example, the official documentation gives the demonstration of mauiAppBuilder.Services.AddTransient<ISettingsService, SettingsService>();. Although this demonstration method is AddTransient, it is still applicable to the AddSingleton method.

Since MainViewModel is not an implementation class of MainPage, a type conversion error occurred when the program was created.

Workaround:

Register these classes individually.

builder.Services.AddSingleton<MainPage>();
builder.Services.AddSingleton<MainViewModel>();
builder.Services.AddSingleton<LoginPage>();
builder.Services.AddSingleton<LoginViewModel>();

Best Regards,

Alec Liu.


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.

Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

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