I'm trying to pass a service to a component constructor in MAUI:
public partial class MyComponent: ContentView
{
public MyComponent(MyService service)
{
InitializeComponent();
data = service.getData();
}
}
But it throws error and asks to add a default constructor:
public partial class MyComponent: ContentView
{
public MyComponent() { }
public MyComponent(MyService service)
{
InitializeComponent();
data = service.getData();
}
}
I added singletons to pass the service to the component:
builder.Services.AddSingleton<MyComponent>();
builder.Services.AddSingleton<MyService>();
I also tried this method:
builder.Services.AddSingleton(sp => new MyComponent(sp.GetService<MyService>()));
None of them worked. Only default constructor called
I use the component in a page like this:
<ContentPage ...
xmlns:components="clr-namespace:MyApp.Components">
<components:MyComponent/>
</ContentPage>
How do I pass a service to a component?