0

Please see the code below:

public partial class MyContentPage : ContentPage
    {

        public CreditCardView()
        {
            InitializeComponent();
        }
}

It works as expected. Now say I want to inject a dependancy:

public partial class MyContentPage : ContentPage
    {
        private readonly IMyService _myService;

        public CreditCardView(IMyService myService)
        {
            InitializeComponent();
            _myService=myService;
        }
}

With the second excerpt of code I see a compilation error: "The given key was not present in the dictionary". What is the problem? I have registered the dependancy.

w0051977
  • 15,099
  • 32
  • 152
  • 329
  • XAML pages require a default constructor – Jason Sep 11 '19 at 15:29
  • @Jason, thanks. Is it not possible to use a parameterized constructor (with a default constructor)? – w0051977 Sep 11 '19 at 15:30
  • in C# the default constructor is parameterless. It would probably make more sense to inject your service into your VM, not directly into the page. That would avoid this problem – Jason Sep 11 '19 at 15:33
  • I agreee with Jason. If for some reason you still want to access your service within your view you might want to use Xamarin.Forms [DependencyService](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/dependency-service/introduction). The cleaner approach would be to use MVVM and inject the service into your ViewModel – Mouse On Mars Sep 11 '19 at 17:32

0 Answers0