Diego Venâncio
Diego Venâncio

Reputation: 6007

xamarin forms mvvm Missing default constructor for

I have create a MessageCenterService interface

public interface IDialogService
{
    Task Toasting(string title);
}

public class DialogService : IDialogService
{
    public async Task Toasting(string title)
    {
        using (var Dialog = UserDialogs.Instance.Toast(title, null))    
        {
            await Task.Delay(1000);
        }
    }
}   

Now I'm trying dependency inject but:

public class LoginViewModel : BaseViewModel
{
    private IDialogService _dialogService;

    public ICommand LoginCommand { get; set; }

    public LoginViewModel(IDialogService dialogService)
    {
        _dialogService = dialogService;
        LoginCommand = new Command(Login);  
    }
}   

Erro => Missing default constructor for "..LoginViewModel"

LoginPage.xaml

  <ContentPage.BindingContext>
        <viewModels:LoginViewModel/>
  </ContentPage.BindingContext>

But if I put:

public LoginViewModel(){}

public LoginViewModel(IDialogService dialogService) //:Base() :this
{
    _dialogService = dialogService;
    ...
}

Error disappear but IDialogService never is instantiate _dialogService always null

LoginPage.xaml.cs changes not working too..

public LoginPage()
{
    InitializeComponent();
}

public LoginPage(IDialogService dialogService): base()
{
    InitializeComponent();
}

I am missing something? Thanks in advance

https://forums.xamarin.com/discussion/48009/pop-display-alert-message-from-viewmodel Missing Default Constructor error in Xamarin Forms Xamarin Forms -> System.MissingMethodException: Default constructor not found for [Interface] Missing Default Constructor error in Xamarin Forms

Upvotes: 1

Views: 779

Answers (2)

Ilnam Jeong
Ilnam Jeong

Reputation: 399

Try to use the DependencyService or 3rd party libraries like TinyIOC. Here is my sample code using the DependencyService. You can register your service using DependencyService.Register<>() and simply invoke it using DependencyService.Get<>();

App.xaml.cs

public App()
{
   ...
   DependencyService.Register<DialogService>();
   ...
}

LoginPage.xaml.cs

LoginPage()
{
   InitializeComponent();
   BindingContext = new LoginViewModel();
}

LoginViewModel.cs

private IDialogService _dialogService;

public LoginViewModel()
{
   ...
   _dialogService = DependencyService.Get<DialogService>();;
   ...
}

Upvotes: 3

Achon
Achon

Reputation: 105

try private readonly IDialogService _dialogService;

Upvotes: 0

Related Questions