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. 
  • Links to .App.iOS Libraries.iOS Forms
  • Forms.App Library Links
  • Libraries.iOS library links
  • Links Forms.App.iOS 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 get the dependency service to find an interface implementation? I need to have them in a separate project, because I need the same implementations in different projects.

+7
c # dependency-injection xamarin xamarin.forms
source share
6 answers

Solved it by creating a static class with an empty Init method. And the method call at the beginning of the AppDelegate.FinishedLaunching method.

+2
source share

Adding some additional information. This seems to be a bug related to the binding in the library that defines the dependency service, as described here .

I solved the problem by manually creating an instance of the iOS dependency service.

In your iOS project, in the AppDelegate.cs application, FinishedLaunching, create an implementation object for the iOS dependency service, for example.

 var obj = new Company.Project.iOS.NativeImplementation_iOS (); 

It worked for me.

+5
source share

I had

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

where i should have been

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

Therefore, always do the implementation, not the interface in your specific platform code! Otherwise you will receive

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

+5
source share

If you get a null value for your dependency, another reason may be that your type is similarly called your service, and the wrong type is declared in Dependency. At least that was for me.

+3
source share

This is because the implementation of Interface.cs does not contain an empty constructor.

For DependencyService to work, you MUST have an empty constructor as follows:

 public Interface(){} 

Your FormsApp solution will have to reference the solution containing the interface declarations.

+2
source share

Perhaps make sure you reference both the PCL library and the cross platform library

 Forms.App.iOS references - Libraries references - Libraries.iOS 

It worked for me

0
source share

All Articles