Dependency Service Objects

MohammadMohammadiKhahMohammadMohammadiKhah USMember
edited March 29 in Xamarin.Forms

Hi all,
I have a Interface like below

public interface ICalculator
{
        void setNum(int num);

        void getWidth();
}

and i implemented a class in Xamarin.Android using that interface like below

[assembly: Xamarin.Forms.Dependency(typeof(Calculator))]namespace Test.Droid
{
    class Calculator: IClaclulator
    {
        private int base = 0;

        public void setNum(int num)
        {
            base = num;
        }

        public int getBase()
        {
            return base;
        }
    }
}

but when i load this class in MainPage with DependencyService like this code

public partial class MainPage  ContentPage
{
    public MainPage()
    {
        InitializeComponent();
        ICalculator icalculator = DependencyService.Get<ICalculator>(DependencyFetchTarget.GlobalInstance);
        icalculator.setNum(10);
        int result = icalculator.getBase();
    }
}

The result should be 10, but it seems that after setNum(10) the num variable in Calculator class will update but after calling getBase() num variable in class is not in memory and it will return default value which is 0;

Answers

  • JamesLaveryJamesLavery GBBeta, University ✭✭✭✭✭
    You have defined the method setNum but are calling setNume - note the 'e' on the end.

    However I'm not sure this would compile! Is it a typo in your posted code?
  • @JamesLavery said:
    You have defined the method setNum but are calling setNume - note the 'e' on the end.

    However I'm not sure this would compile! Is it a typo in your posted code?

    This was a typo error. the code can compile but the logic has error.

  • JamesLaveryJamesLavery GBBeta, University ✭✭✭✭✭

    From the code you've posted (with the typo corrected), this is indeed strange. Are you sure you aren't creating a new instance of the Droid class? I suggest you create a constructor for it and set a breakpoint to check when it's being instantiated.

  • jezhjezh Member, Xamarin Team Xamurai

    There are several errors in your code.
    1. since the word base is a keywords, we can't use it as a variable. For example , we can change it like this.

        private int number = 0;
    

    2. When you called the code: int result = icalculator.getBase(); , but I couldn't see the declaration of this method in public interface ICalculator ,so we should add the method getBase as follows:

     public interface ICalculator
      {
        void setNum(int num);
        void getWidth();
         int getBase(); // add method: getBase()
      }
    

    The effect is as follows:

    I have created a simple demo in the attachement, you can check it.

  • jezhjezh Member, Xamarin Team Xamurai

    @MohammadMohammadiKhah

    Have you resolved your problem?

Sign In or Register to comment.