Multiplatform .NetStandard library with native binding

noobsoftware 251 Reputation points
2020-11-23T15:10:23.163+00:00

I'm trying to create a multiplatform .NetStandard library from a Xamarin.Forms application i have made. In the Xamarin.Forms application i used dependency injection, which i'm assuming from what i've read is not available for .NetStandard libraries so i'm mimicking this project:

https://github.com/jfversluis/FilePicker-Plugin-for-Xamarin-and-Windows/blob/master/src/Plugin.FilePicker/CrossFilePicker.shared.cs

It uses an Interface and then declares class implementation for each platform. My question is: How does the constructor, on line 43 in the git code, know which implementation to use? (depending on the platform)

And i also need to use a native binding for objective-c code, i tried adding the binding project to the .NetStandard library project and referencing it from there but i get the following message:

(Incompatible target framework: Xamarin.Mac, Version=v2.0)

Is it not possible to add objective-c code binding to a .NetStandard library or is there some other way to go about it?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,288 questions
0 comments No comments
{count} votes

Accepted answer
  1. Joe Manke 1,091 Reputation points
    2020-11-23T16:32:37.977+00:00

    Dependency injection just means that you do not create instances of your dependencies, you get them from somewhere else, whether that means constructor arguments, method arguments, or pulling them out of a container. It is possible, and indeed necessary, for .NET Standard projects. Xamarin.Forms app is a perfect example.

    The project you're looking at uses the bait-and-switch technique. What happens is project is compiled several times for different target frameworks, but all have the same assembly name. For each configuration, only certain files are included. For the .NET Standard builds, only the files with a .shared.cs extension are included, for iOS it's the .shared.cs files and FilePickerImplementation.ios.cs, etc. When you add the NuGet package to your solution, each project gets the DLL that matches its own target framework. The .NETStandard DLLs are just placeholders so that your .NETStandard projects can compile, but they would not actually run on their own because there is no implementation of IFilePicker and a NotImplementedException will be thrown when you access CrossFilePicker.Current. However, when you compile the whole solution for iOS, the iOS version of the DLL is used instead of the .NETStandard version so there is an implementation.

    You cannot directly reference a binding project from a cross-platform project, that is exactly what dependency injection is for.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful