C# Plugin Guide
The C# side of a Napacitor plugin is a plain net10.0 class library with one class marked [NapacitorPlugin]. Because the native layer is a .NET MAUI Blazor host, the same C# code runs on Android, iOS, Mac Catalyst, and Windows — there is no per-platform native project to write.
The Plugin Class
Create a class that extends NapacitorPluginBase and mark it with [NapacitorPlugin]:
using Napacitor.Plugins;
namespace Napacitor.Plugins.Echo;
[NapacitorPlugin("Echo")]
public class EchoPlugin : NapacitorPluginBase
{
[NapacitorMethod]
public Task<EchoResult> Echo(EchoOptions options)
{
return Task.FromResult(new EchoResult { Value = options.Value });
}
}
[NapacitorPlugin]optionally takes the plugin name. If omitted, the class name minus thePluginsuffix is used (EchoPlugin→"Echo"). This name must match the name passed toregisterPluginon the JS side (case-insensitive).- Every public method marked
[NapacitorMethod]becomes callable from JavaScript; unmarked public methods are not exposed. - The runtime discovers the plugin by reflection — do not register anything manually.
Host discovery requirements
- The project's
AssemblyNamemust start withNapacitor(e.g.Napacitor.Echo), otherwise the runtime's assembly scan will not find it. - The host must reference the plugin project. This happens automatically:
nap syncregeneratesmaui/napacitor.build.propswith a<ProjectReference>for every installed@napacitor/*plugin'smaui/project. - The class needs a public parameterless constructor.
Method Signatures
The bridge supports exactly three shapes (see Method Types):
| Shape | Example | Use when |
|---|---|---|
| No parameters | public Task<int> GetCount() | No input required. |
| One typed DTO | public Task<EchoResult> Echo(EchoOptions options) | Structured input; deserialized with NapacitorJson (camelCase, case-insensitive). |
One NapacitorCall | public Task<object?> Raw(NapacitorCall call) | You need the raw JSON JsonElement arguments. |
Methods with more than one parameter throw InvalidArguments. Return values can be void, Task, Task<T>, ValueTask, or ValueTask<T> — the bridge awaits them and unwraps the result automatically.
Serialization
C# property names are serialized to camelCase JSON automatically (BatteryLevel → batteryLevel), and deserialization is case-insensitive in both directions. Dates follow ISO 8601. See Data Types for the full rules.
Errors
Throw NapacitorException with a code; the JS promise rejects with a NapacitorException carrying the same code and message:
[NapacitorMethod]
public Task DoSomething()
{
throw new NapacitorException(NapacitorException.Unavailable, "Not available on this device");
}
Common codes: Error (default), Unavailable, NotImplemented, InvalidArguments, Canceled, PluginNotFound. For the common "not implemented on this platform" case, NapacitorPluginBase provides a helper:
[NapacitorMethod]
public Task SomePlatformSpecificThing() => throw NotImplemented("somePlatformSpecificThing");
Any other unhandled exception is wrapped into an error envelope with code Error and its message — but prefer throwing NapacitorException explicitly.
Plugin Events
To push repeated updates to JavaScript (the equivalent of Capacitor's keepAlive calls), use the event pipeline (see Plugin Events):
[NapacitorPlugin("Battery")]
public class BatteryPlugin : NapacitorPluginBase
{
private const string StatusChangeEvent = "batteryStatusChange";
// Subscribe to the native source only while JS listeners exist.
protected override void OnListenerAdded(string eventName)
{
if (eventName == StatusChangeEvent)
Battery.Default.BatteryInfoChanged += OnBatteryInfoChanged;
}
protected override void OnListenerRemoved(string eventName)
{
if (eventName == StatusChangeEvent)
Battery.Default.BatteryInfoChanged -= OnBatteryInfoChanged;
}
private void OnBatteryInfoChanged(object? sender, BatteryInfoChangedEventArgs e)
{
NotifyListeners(StatusChangeEvent, new BatteryInfoResult
{
BatteryLevel = Math.Clamp(e.ChargeLevel, 0.0, 1.0),
IsCharging = e.PowerSource != BatteryPowerSource.Battery,
});
}
}
NotifyListeners(eventName, data)pushes a payload to every JS listener of that event.OnListenerAdded/OnListenerRemovedfire when the first/last JS listener registers/removes — use them for lazy subscription to native event sources.ListenerCount(eventName)reports the current listener count.- For global DOM events instead of plugin events, use
TriggerJSEventAsync(see the Runtime API).
Accessing Configuration
napacitor.config.json values are available on the base class:
Config— the plugin's own section (plugins.<PluginName>), possibly empty.AppConfig— the entire config file.Platform— current platform string:android/ios/mac/windows.
var apiKey = Config.TryGetProperty("apiKey", out var prop) ? prop.GetString() : null;
See Configuration Values.
Project Setup
maui/Napacitor.Echo.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>Napacitor.Plugins.Echo</RootNamespace>
<AssemblyName>Napacitor.Echo</AssemblyName>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Maui.Essentials" Version="10.0.20" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\maui\src\Napacitor.csproj"
Condition="Exists('..\..\maui\src\Napacitor.csproj')" />
<ProjectReference Include="..\..\..\maui\src\Napacitor.csproj"
Condition="!Exists('..\..\maui\src\Napacitor.csproj')" />
</ItemGroup>
</Project>
The dual ProjectReference resolves the @napacitor/maui runtime in both layouts: inside the monorepo (plugins/<p>/maui/) and inside node_modules (node_modules/@napacitor/<p>/maui/). The plugin project is compiled as part of the host build — it is not built standalone.
Microsoft.Maui.Essentials (DeviceInfo, Battery, Connectivity, …) is the main source of native APIs. For anything beyond Essentials, use platform-specific code guarded by OperatingSystem.IsAndroid() / IsIOS() / etc., or multi-target the plugin project with platform TFMs.