Disclaimer: I’m very new to IOC, DI, and FreshMvvm. Just got this working for myself and wanted to share to help some others out there just in case they stumbled upon this forum like I did.
DependencyService provided by Xamarin Forms is fantastic, yet still limited (e.g. cannot implement constructor injection). It also can become a bit of a hassle to implement Unit Testing while making use of DependencyService. Here is a tutorial that will take you through some steps if you insist on using DependencyService but also want to unit test your code. It is a service locator, which is more difficult (in my opinion) to test than Dependency Injection is.
Instead of using that, I just used FreshMvvm’s IOC to access platform specific code. Everything @WickedW said is completely right. I just tweaked the last step a little.
Instead of resolving the dependencies directly:
IFileHelper fileHelper = FreshMvvm.FreshIOC.Container.Resolve<IFileHelper>();
string dbPath = fileHelper.GetLocalFilePath("CoreSQLite.db3");
I used constructor injection:
Public class MainPageModel : FreshBasePageModel
{
public string YourLabelText { get; set;}
IFileHelper _fileHelper;
public MainPageModel(IFileHelper fileHelper)
{
_fileHelper = fileHelper
}
public override void Init(object initData)
{
YourLabelText = _fileHelper.GetLocalFilePath(“CoreSQLite.db3”);
}
}
Make sure to register your platform specific class before you load the app:
FreshMvvm.FreshIOC.Container.Register<IFileHelper, FileHelper>();
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
I had to do that because I resolve my MainPageModel in the constructor of my App.xaml.cs:
public App()
{
InitializeComponent();
var page = FreshPageModelResolver.ResolvePageModel<MainPageModel>();
var navContainer = new FreshNavigationContainer(page);
MainPage = navContainer;
}
@WickedW had the platform specific implementation completely on point, then I just used Michael Ridland’s FreshMvvm n=2 video to figure out constructor injection because it was a feature I needed personally. Hope this helps people who struggled to figure this out like myself 😊.