lsaudon
lsaudon

Reputation: 1458

DependencyService

I need DependencyService to use specific android functionality.

After Debug I see DependencyService is call, App is called too.

Why DependencyService.Get<T>() call App() ?

IMyService.cs

namespace SampleM3Scan.MobileApp.Services
{
    public interface IMyService
    {
    }
}

MyService.cs

using Android.Content;
using App1.MobileApp.Droid;
using App1.MobileApp.Services;
using Xamarin.Forms;

[assembly: Dependency(typeof(MyService))]
namespace App1.MobileApp.Droid
{
    internal class MyService : IMyService
    {
        private readonly MyReceiver _myReceiver = new MyReceiver();

        public class MyReceiver : BroadcastReceiver
        {
            private readonly App app = new App();

            public override void OnReceive(Context context, Intent intent)
            {
                MessagingCenter.Send(app ,"item", intent.GetStringExtra("item"));
            }
        }
    }
}

MainPage.xaml.cs

using System.ComponentModel;
using App1.MobileApp.Pages.Base;
using App1.MobileApp.Services;

namespace App1.MobileApp.Pages.Main
{
    [DesignTimeVisible(false)]
    public partial class MainPage : PageBase
    {
        public MainPage()
        {
            InitializeComponent();
            var myService = DependencyService.Get<IMyService>();
            BindingContext = new MainPageViewModel(myService);
        }
    }
}


Upvotes: 0

Views: 166

Answers (1)

pix
pix

Reputation: 1290

var myService = DependencyService.Get<IMyService>();

Will Give an instance of your IMyService. In your case the IMyService will create a new MyService As you can see in you MyService you have the following line :

 private readonly App scanApp = new App();

New App is created each time you will need to create a new MyService Class instance.

Upvotes: 1

Related Questions