Reputation: 201
this is my situation.
I have an app written in Xamarin that supports both Droid and iOS. Each of these projects require platform independent Bluetooth API. So, what I've done is create an interface that I use with a DependencyService. The field I need is a list of Bluetooth Devices... this is simple enough if I'm developing for one platform. But in this case, my Bluetooth implementation "detects" devices on it own thread, so it's not necessarily possible for me to return a String[] Names.. My solution was this, I create a class and within the class have a String[] and since the class is a "reference" I assumed as I add to the list later in the code the changes would reflect in my DependencyService... but sadly, no, this is not the case..... Here's some code for the situation.
This is the definition of my class that I 'harbor' my array of items in.
namespace ThoughtCastRewrite.BluetoothX
{
public class BluetoothItems
{
public string[] ListBTItems = new string[10];
public BluetoothItems()
{
ListBTItems[2] = "TEST";
ListBTItems[6] = "WtF?";
}
public void Set(string stringToAdd)
{
ListBTItems[4] = stringToAdd;
}
}
}
This bit of code is in the Cross-Platform project
BluetoothItems bluetoothItemList = DependencyService.Get<ISlateBluetoothItems>().IBluetoothTest;
listView.ItemsSource = bluetoothItemList.ListBTItems;
Now here is the Droid code:
BluetoothItems bluetoothItems = new BluetoothItems();
public BluetoothItems IBluetoothTest { get => bluetoothItems; }
Ok, so, this may seem obvious, but TEST and WtF? are added to my listview. But, in my MainActivity (Droid portion again) after the entire view loads I call
bluetoothItems.Set("TEST");
and the "TEST" item is never added to my list!
Am I being clear here about what I'm trying to do?
Any assistance is welcomed.
Upvotes: 1
Views: 145
Reputation: 33048
The DependencyService
implementation will always create a new instance. That is either a global instance or a new instance for every call to Resolve()
. You can configure the behavior by setting the DependencyFetchTarget
(see docs).
No matter how you configure it, the concrete BluetoothItems
instance you are creating is not the one that will be returned by Resolve()
. That's why the item you add won't be part of what you get in your shared code.
If you’d like to get different behavior and return precreated instances, the out of the box solution won’t work. You will have to create your own logic or use one of the many other dependency injection options out there. For example you could give SimpleIoC a try which I have used in many projects (it is part of MvvmLight).
Upvotes: 2