问题
I am trying to set up DependencyService to call platform specific code in a Multiplatform project.
When calling Dependency.Get<IService>()
in the Shared project I get null.
The Service inside iOS does not seem to register.
I have tried to register it like this: [assembly: Dependency(typeof(Service))]
- on top of the namespace declaration inside the iOS project. Which I have gotten to work inside a Xamarin.Forms project. And I have also tried to call DependencyService.Register<Service>();
inside a Init method in the iOS project - calling it from a Xamarin.Forms iOS project in AppDelegate - made for testing the library.
The Shared
project and iOS
project does not seem to share the same DependencyService
.
How can I call platform specific code in the iOS project from the Shared project with DependencyService?
Edit
I am getting System.PlatformNotSupportedException
when working in visual studio on windows - trying to use DependencyService inside a net standard library project. Could it be that visual studio for mac simply doesn't throw error and returns null instead?
回答1:
You can easily solve the problem by removing Shared project and changing
MyMutliplatformLibraryProject.Run.Test();
to
MyXamarinFormsProject.Run.Test();
If you are trying to create a Nuget with custom controls you can follow this tutorial how to do it.
With .NET standard you don't need to have a shared project. The only obstacle I can see that you are targeting multiple targets. Why don't you start simple and later adjust it?
Long story short. Let's assume you want a NuGet for Xamarin.Forms app, with iOS & Android. You simply need .NET standard, iOS & Android dll. That's all. Later you can create a package with nuspec
来源:https://stackoverflow.com/questions/57073400/dependencyservice-in-multiplatform-library-project