I would like to use DependencyService
using Xamarin.Forms
in a Portable Class Library
. In this case, the PCL is my business logic, and thus, I don't have access to nor want to install Xamarin.Forms
in this project.
What I'm trying to do in my business logic is:
_login = DependencyService.Get<ILogin>();
I am using SimpleContainer
for registration of my services.
My question is thus, which Service Locator
can I use in my business logic project?
If you don't want to install Xamarin.Forms
in your PCL
you can still program against your platform-specific implementations in your PCL
.
Normally, like you mentioned, you could access the platform-specific class instance in your PCL
project using something like:-
_login = DependencyService.Get<ILogin>();
However this creates a dependency on Xamarin.Forms
.
To get around this you can implement your interface ILogin
in the PCL
.
You will then create a static class with either one of the following, depending if it is a global reference (with only one instance ever existing), or whether you want a new instance of your platform-specific class implementation instantiated for use within the PCL
project:-
Option 1 : Create a single, global instance, that every call in your PCL
goes through
To do this, add the following to your PCL
:-
public static MyGlobal
{
public static ILogin MyLoginGlobalInstance;
}
Then in your initialization of your platform-specific iOS and Android projects you can set this global property in your PCL
matching a new instance created in each of the platform-specific projects, such as:-
MyPCLProject.MyGlobal.MyLoginGlobalInstance = new Login();
By creating it on the local platform-specific project, and setting this in the PCL
, you can then access the instance within the PCL
according to your interface as you have defined in ILogin
along the lines of:-
MyPCLProject.MyGlobal.MyLoginGlobalInstance.{some interface member}
Option 2 : Create a new instance of your platform-specific class instance, every time in your PCL
.
If however, you want to create a new instance of your platform-specific class everytime you need it, in your PCL
, you can do the following.
In your PCL
create the following:-
public static MyGlobal
{
public static Func<ILogin> CreateNewInstance_Login;
}
Then, in your platform-specific project you can initialize this function with something along the lines of:-
MyPCLProject.MyGlobal.CreateNewInstance_Login = new Func<ILogin>(()=>
{
return new Login();
}
Then to consume and create a new instance each time within your PCL
you create a new instance by calling:-
ILogin objMyLoginInstance = MyPCLProject.MyGlobal.CreateNewInstance_Login();
objMyLoginInstance.{some interface member}