Musaffar Patel
Musaffar Patel

Reputation: 1372

"No parameterless constructor defined" error when attempting DI

I am trying to register a class for dependency inject, however when I tried to inject it through my constructor I get the following error:

System.MissingMethodException: No parameterless constructor defined for type 'MauiClient.MainPage'

I register my service in the main program file as follows:

MainProgram.cs:

using Accounting.Shared.Services;
using Microsoft.Extensions.Logging;

namespace MauiClient
{
    public static class MauiProgram
    {
        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.AddTransient<ITestService>(s =>
            {
                var httpClient = new HttpClient();
                var token = "";
                return new TestService(httpClient, token);
            });

            return builder.Build();
        }
    }
}

My actual service class - TestService.cs:

namespace Accounting.Shared.Services;

public interface ITestService
{
}

public class TestService : ITestService
{
    private HttpClient _httpClient;
    private string _token;

    public TestService(HttpClient httpClient, string token)
    {        
        _httpClient = httpClient;
        _token = token;
    }
}

And finally in MainPage.xaml.cs I attempt the dependency injection:

namespace MauiClient;

using Accounting.Shared.Services;

public partial class MainPage : ContentPage
{
    int count = 0;

    private ITestService _testService;

    public MainPage(ITestService testService)
    {
        InitializeComponent();
        _testService = testService; 
    }

    private void OnCounterClicked(object sender, EventArgs e)
    {
    }
}

I cannot see why it's failing to pass it as a parameter. Any help would be appreciated.

Upvotes: 1

Views: 509

Answers (1)

Julian
Julian

Reputation: 8934

You need to register not only the ITestService, but also the MainPage, when using it with <ShellContent>:

builder.Services.AddTransient<ITestService>(s =>
{
    var httpClient = new HttpClient();
    var token = "";
    return new TestService(httpClient, token);
});

builder.Services.AddTransient<MainPage>();

return builder.Build();

This is because Shell can only use parameterless constructors on its own.

Upvotes: 1

Related Questions