I'm trying to understand how to implement dependecy injection in a .NET MAUI app.
I have a service class -- and its interface -- that handle my REST calls that looks like this:
public class MyRestApiService : IMyRestApiService
{
public async Task<string> Get()
{
// Do someting
}
}
I then place this in my DI container in MauiProgram.cs
:
builder.Service.AddTransient<IMyRestApiService, MyRestApiService>();
I also have a view model that I will use for my MainPage.xaml
. The question is, if I do a constructor injection of my service, the XAML doesn't seem to like it.
The MainPageViewModel
looks like this:
public class MainPageViewModel : BaseViewModel
{
IMyRestApiService _apiService;
public MainPageViewModel(IMyRestApiService apiService)
{
_apiService = apiService;
}
}
When I tried to define MainPageViewModel
as the view model for MainPage.xaml
as below, I get an error:
<ContentPage.BindingContext>
<vm:MainPageViewModel />
</ContentPage.BindingContext>
The error reads:
Type MainPageViewModel is not usable as an object element because it is not public or does not define a public parameterless constructor or a type converter.
How do I inject my services into my view models?