Hello Devz,
Xamarin.Forms have its own Dependency Injection implementation. Of course you can still use other ones like MvvmCross, Ninject and so on, but they will ask you a bit more configuration and changes in your code. The one from Xamarin.Forms works pretty well and is really simple to use.
Here is a simple example. Let’s say you have a BL (Business Layer) which wants to call a DL (Data Layer), but loosely coupled.
Just above the namespace of your DL, add this:
[assembly: Dependency(typeof(NAME_OF_YOUR_DL))]
It will mark your class as resolvable for the DI resolver. This “Dependency” keyword comes from Xamarin.Forms library.
Then create an Interface representing the contract of your DL, defining all the methods you want to expose.
And in the DL, implement all the methods from the Interface:
using Xamarin.Forms; [assembly: Dependency(typeof(UserDL))] namespace MyApp.DL { public class UserDL : IUserDL { ...
And the when you need to call this DL in your BL, just do it like that:
public class UserBL { IUserDL userDL; public UserBL() { userDL = DependencyService.Get<IUserDL>(); userDL.GetAll(); //GetAll() should be an async call of course //But hey, it's an example... :) }
Depending on the Xamrain.Forms version you’re running, it is possible that the DependencyService.Get returns NULL. In that case, you have to open your App.xaml.cs file and add just after the InitializeComponent:
DependencyService.Register<UserDL>();
Happy coding! 🙂