Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Dependency Service Issue

In Xamarin Forms i have a solution like this:

Solution
 |- Libraries
 |   |- IInterface.cs
 |   |- Etc.
 |
 |- Libraries.iOS
 |   |- Interface.cs
 |   |- Etc.
 |
 |- Forms.App
 |   |- App.cs
 |   |- Etc.
 |
 |- Forms.App.iOS
 |   |- Etc.
  • Forms.App.iOS references Libraries.iOS
  • Forms.App references Libraries
  • Libraries.iOS references Libraries
  • Forms.App.iOS references Forms.App

IInterface.cs

namespace a
{
  public interface IInterface
  {
    void Function ();
  }
}

Interface.cs

[assembly: Xamarin.Forms.Dependency(typeof(a.Interface))]
namespace a
{
  public class Interface : IInterface
  {
    public void Function ()
    {
      return;
    }
  }
}

App.cs

namespace a
{
  public class App
  {
    public static Page GetMainPage ()
    {
      var inter = DependencyService.Get<IInterface> (); // This is always null.
      return new ContentPage { 
        Content = new Label {
        Text = "Hello, Forms!",
        VerticalOptions = LayoutOptions.CenterAndExpand,
        HorizontalOptions = LayoutOptions.CenterAndExpand,
        },
      };
    }
  }
}

How can i make the dependency service locate my Interface implementation? I need to have them in a separate project because i need the same implementations in different projects.

like image 902
BisaZ Avatar asked Nov 27 '14 14:11

BisaZ


1 Answers

I had

[assembly: Dependency(typeof(TestService.IMyService))]

, where I should have

[assembly: Dependency(typeof(TestService.iOS.MyService))]

So always take the implementation and not the interface in your platform specific code! Otherwise you get

System.MissingMethodException: Default constructor not found for [Interface]

like image 116
testing Avatar answered Oct 03 '22 21:10

testing