I'm testing uno platform solution to see if it's flexible enough and can integrate pre existing autofac (6.2.0) and Autofac.Extras.CommonServiceLocator(6.0.1) stuff in it. I want to add the ViewModelLocator to auto resolve view models. it's working with UWP and wpf project, but not with droid or WASM. I added in shared app.xaml the resource
<Application
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<XamlControlsResources xmlns="using:Microsoft.UI.Xaml.Controls" />
<!-- #Region MVM light view model locator -->
<ResourceDictionary>
<local:ViewModelLocator x:Key="ViewModelLocator" d:IsDataSource="True" />
</ResourceDictionary>
<!-- #Endregion -->
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
In the mainpage.xaml
DataContext="{Binding [TestViewModel], Source={StaticResource ViewModelLocator}}"
whit this configuration the constructor is called at startup where I also want to set up Inversion of control stuff
public ViewModelLocator()
{
this._container = IOCContainerConfig.Configure();
var serviceLocator = new AutofacServiceLocator(this._container);
ServiceLocator.SetLocatorProvider(() => serviceLocator);
//this._dbContext = serviceLocator.GetInstance<IContext>();
//TestDbConnection(this._dbContext);
}
As said this is not working with other kind of projects like droid or wasm the constructor of the locator is never called but I don-t have errors, just page is loaded without the viewmodel behind.
Any ideas or tips to make it working for all projects?
Depending on the type of resource, Uno Platform is initializing some resources in a ResourceDictionary lazily only when they are accessed. This is done as a performance optimization.
To guarantee that the
ViewModelLocatorconstructor is always called on all platforms, it may be better to call it from code, eg from theAppconstructor inApp.xaml.cs.