LightInject icon indicating copy to clipboard operation
LightInject copied to clipboard

Xamarin Forms Casting Exception in LoadApplication

Open DumiduM opened this issue 6 years ago • 5 comments

`var container = new ServiceContainer();

        container.Register<WardListPage>();
        container.Register<WardListViewModel>();
        container.Register<WardListService>();

        container.Register<PatientListViewPage>();
        container.Register<PatientListViewModel>();
        container.Register<PatientService>();

        container.Register<PatientDetailsViewPage>();
        container.Register<PatientDetailsViewModel>();

        var instance = container.GetInstance<WardListPage>();

        MainPage = new **NavigationPage(instance);`**

Getting exeption : System.InvalidCastException: Specified cast is not valid. when calls LoadApplication(new App()); in Xamarin.Forms

when calling the instance as a NavigationPage this happens. when MainPage = instance it works fine.

Do you have any idea why this happens?

DumiduM avatar Dec 21 '18 06:12 DumiduM

Could you provide a simple repro?

seesharper avatar Jan 24 '19 13:01 seesharper

I don't understand what is happening here, but when registering a Xamarin.Forms page with the generic, container.Register<SomePage>(), vs using the factory, container.Register(x => new SomePage(x.GetInstance<SomeViewModel>()) the resulting ToolbarItems property on the Page is converted from an ObservableCollection<> to a List<> which then causes the InvalidCastException. I will try to get a simple repro made.

jordansjones avatar Aug 14 '20 02:08 jordansjones

Here is a reproducible example: https://github.com/jordansjones/LightInjectErrorExample The main area of concern is here: https://github.com/jordansjones/LightInjectErrorExample/blob/de7334f17c67532acf37abc0a833c2632fbf1617/LightInjectErrorExample/LightInjectErrorExample/App.xaml.cs#L17-L34

Here is the ToolbarItems on the Xamarin.Forms Page that is getting changed: https://github.com/xamarin/Xamarin.Forms/blob/daa0589999171cfc153a915ca122b6e80d7948c4/Xamarin.Forms.Core/Page.cs#L130 And here is the initialization of that property: https://github.com/xamarin/Xamarin.Forms/blob/daa0589999171cfc153a915ca122b6e80d7948c4/Xamarin.Forms.Core/Page.cs#L62-L64

jordansjones avatar Aug 14 '20 03:08 jordansjones

So it works when using the factory?

seesharper avatar Aug 14 '20 14:08 seesharper

Yes. Meaning, the ObservableCollection isn't replaced with a List when using the factory.

jordansjones avatar Aug 15 '20 01:08 jordansjones