Developing Reusable Cross-Platform Plugins for Xamarin
Alan Grgic
@spellgrgicright
code-sharing techniques for creating universal packages





A Little About Me
- Software Development
- Board Games
- Metal Music
- Corgis
- Beverages
Sharing is Caring

Why do we love Xamarin?
Xamarin API Landscape
Platform-Specific APIs
Commonalities in Platform-Specifics
- Vibration
- GPS
- Accelerometer
- Local File System
- Battery Info
- Flashlight
- Phone Dialer
- etc.

The Missing Piece?
Shared Non-UI SDK Functionality.

Platorm-Specifics
Xamarin
netstandard
A Review of Some Abstraction Techniques
- Service Locator Pattern
- Factory Pattern
Service Locator Pattern
Service Locator Example
Factory Pattern
Factory Pattern Example
We want our code to be reusable in packages across projects though...
Plugin Architecture
- Move all the plugin logic into separate projects
- Platform-specific projects contain only sdk code
- Plugin.Shared is referenced by all other projects
- PluginImpl implements the IPlugin interface
- CrossPlugin is a singleton factory of PluginImpl
Plugin Example
How Can this Possibly Work?

Look closely... Platform Code is never referenced directly!
Native SDK
netstandard business logic
netstandard plugin
???somehow native sdk code executes???
Rules for Creating Xamarin Plugins
- Everything callable from shared code uses the same namespace
- All assemblies have the same name
- All assemblies have the same version number
The "Bait and Switch" technique
- The netstandard project of your plugin is never actually executed.

- By adding a reference to the platform-specific library, the netstandard output project gets overwritten (switched) at build time since we made the two assemblies have the same name and version number!
Packaging for NuGet
- Create a nuspec file that describes our deliverables and dependencies
- Bundle the netstandard dll and each platform dll all together in one pkg
- Each dll is only installed to its corresponding target platform
- Need to install the NuGet pkg on all projects
- From that point, the "Bait and Switch" trick takes over
Anatomy of a nuspec file
Xamarin.Essentials
- One library that contains several common plugins in one pkg
- Linking/tree shaking removes unused plugin code from builds
- Currently in preview and active development
- Source: https://github.com/xamarin/essentials
- Documentation: https://docs.microsoft.com/en-us/xamarin/essentials
Developing Reusable Cross-Platform Plugins for Xamarin
Alan Grgic
@spellgrgicright
Thanks!

Developing Resuable Cross-Platfrom Plugins for Xamarin
By Alan Grgic
Developing Resuable Cross-Platfrom Plugins for Xamarin
code-sharing techniques for creating universal plugins
- 431