Skip to content

Repository files navigation

Shiny Extensions

Dependency Injection Extensions

  • Source generate all attributed classes to a single add file - saves you the boilerplate
  • Factory-form emission - generated registrations expand the constructor at compile time (no reflection, AOT-clean) so resolve chains like OnResolved compose naturally
  • ActivatorUtilities-style constructor selection ([ActivatorUtilitiesConstructor] and [FromKeyedServices] honored)
  • Optional/nullable constructor parameters are respected - resolved via GetService (no throw when unregistered) with fallback to the declared default value
  • Multiple interfaces via explicit forwarders (no reflection)
  • Supports open generics and keyed services
  • OnResolved<T>(hook) chain extension for one-shot post-construction hooks

The Results

THIS:

using Microsoft.Extensions.DependencyInjection;
using Shiny;

// given the following code from a user
namespace Sample
{
    public interface IStandardInterface;

    public interface IStandardInterface2;

    [Service(ServiceLifetime.Singleton)]
    public class ImplementationOnly;

    [Service(ServiceLifetime.Transient, "ImplOnly")]
    public class KeyedImplementationOnly;


    [Service(ServiceLifetime.Singleton)]
    public class StandardImplementation : IStandardInterface;

    [Service(ServiceLifetime.Scoped, "Standard")]
    public class KeyedStandardImplementation : IStandardInterface;

    [Service(ServiceLifetime.Singleton)]
    public class MultipleImplementation : IStandardInterface, IStandardInterface2;

    [Service(ServiceLifetime.Scoped)]
    public class ScopedMultipleImplementation : IStandardInterface, IStandardInterface2;


    [Service(ServiceLifetime.Scoped, "KeyedGeneric")]
    public class TestGeneric<T1, T2>
    {
        public T1 Value1 { get; set; }
        public T2 Value2 { get; set; }
    }
}

GENERATES THIS:

// <auto-generated />
using global::Microsoft.Extensions.DependencyInjection;
using global::Shiny;

namespace Sample
{
    public static class __GeneratedRegistrations
    {
        public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddGeneratedServices(
            this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services
        )
        {
            services.AddSingleton<global::Sample.ImplementationOnly>();
            services.AddKeyedTransient<global::Sample.KeyedImplementationOnly>("ImplOnly");
            services.AddSingleton<global::Sample.IStandardInterface, global::Sample.StandardImplementation>();
            services.AddKeyedScoped<global::Sample.IStandardInterface, global::Sample.KeyedStandardImplementation>("Standard");
            services.AddSingletonAsImplementedInterfaces<global::Sample.MultipleImplementation>();
            services.AddScopedAsImplementedInterfaces<global::Sample.ScopedMultipleImplementation>();
            services.AddKeyedScoped(typeof(global::Sample.TestGeneric<,>), "KeyedGeneric");

            return services;
        }
    }
}

Setup

  1. Install the NuGet package Shiny.Extensions.DependencyInjection
  2. Add the following using directive:
    // during your app startup - use your service collection 
    builder.Services.AddGeneratedServices();
  3. Add the [Service(ServiceLifetime.Singleton, "optional key")] attribute to your classes and specify the lifetime and optional key

Serialization

  • Centralized ISerializer backed by source-generated JsonSerializerContexts, no reflection, AOT-clean
  • Shiny.Json static accessor — self-bootstrapping, sibling to Shiny.Stores for mobile cold-start
  • [ShinyJsonContext] on any user-declared JsonSerializerContext partial → source generator emits a [ModuleInitializer] that auto-registers it. No services.AddJsonContext(...) boilerplate needed
  • [ShinyJsonInclude] on a type (or [assembly: ShinyJsonInclude(typeof(T))]) → AOT-safe collection wrappers for List<T>, T[], IEnumerable<T>, IReadOnlyList<T>, IList<T>, ICollection<T>, IAsyncEnumerable<T> — solves the "inline [JsonConverter] works but List<T> fails" trap
  • Multiple contributing libraries chain cleanly via TypeInfoResolverChain. Element types from one context compose with collection wrappers from another
  • services.AddJsonSerialization() / AddJsonContext(...) / ConfigureJsonSerializer(...) for DI-side wiring; Shiny.Json.CreateTestScope() for test isolation

Setup

  1. Install the NuGet package Shiny.Extensions.Serialization
  2. Write a normal STJ source-generator context and decorate it with [Shiny.ShinyJsonContext]:
    using System.Text.Json.Serialization;
    using Shiny;
    
    [ShinyJsonContext]
    [JsonSerializable(typeof(MyDto))]
    [JsonSerializable(typeof(MyOtherDto))]
    internal partial class MyAppJsonContext : JsonSerializerContext;
  3. Done. The generator emits a [ModuleInitializer] calling Shiny.Json.AddContext(MyAppJsonContext.Default) before Main, so both DI consumers and the static Shiny.Json.Default accessor see your types — no services.AddJsonContext(...) call needed.
  4. (Optional) For collection support, mark element types with [ShinyJsonInclude]:
    [ShinyJsonInclude]
    public partial class MyDto { /* ... */ }
    List<MyDto>, MyDto[], IEnumerable<MyDto> and friends now serialize AOT-safely.
// Static access — works before DI exists (useful for mobile cold-start through Shiny.Stores)
var json = Shiny.Json.Default.Serialize(new MyDto { Name = "Allan" });

// DI access — same shared instance
public class MyService(ISerializer serializer) { /* ... */ }

Stores

  • Cross-platform key/value store with support for
    • Android/iOS/Windows - Preferences & Secure Storage
    • Web - Local Storage
    • In Memory
  • Source-generated [Bind] attribute on partial properties - emits getter/setter bodies that round-trip through the store (no INPC required, no runtime reflection, fully AOT)
  • Static Shiny.Stores.Default/Secure/Keyed(...) accessor for direct ad-hoc reads/writes
  • Implement IKeyValueStore to plug in your own store

Setup

  1. Install the NuGet package Shiny.Extensions.Stores

  2. Register at startup — the static Shiny.Stores accessor self-bootstraps on first use:

    builder.Services.AddShinyStores();
    var host = builder.Build();

    On Blazor WebAssembly (where LocalStorageKeyValueStore needs IJSRuntime), also call host.Services.UseShinyStores() after Build() to snapshot the DI-resolved store into the static accessor.

    AddShinyStores() registers IKeyValueStore keyed under StoreKeys.Default and StoreKeys.Secure, plus the default store unkeyed. The unkeyed registration exists for third-party container adapters that predate .NET 8 keyed services — Prism's DryIoc container, for example, still sits on DryIoc 5.x, silently ignores [FromKeyedServices], and resolves the plain IKeyValueStore instead. On those containers, use the static Shiny.Stores.Secure / Shiny.Stores.Keyed(...) accessor when you need a non-default store, since the key will be dropped.

  3. Define your settings as a partial class with [Bind] partial properties:

    using Shiny;
    
    [Singleton]
    public partial class AppSettings
    {
        [Bind]                       // default store
        public partial string Theme { get; set; }
    
        [Bind("secure")]             // secure store
        public partial string Token { get; set; }
    }
  4. Inject AppSettings anywhere. Set properties — they persist. Read properties — they come from the store.

Or skip the class and use the static accessor:

Shiny.Stores.Default.Set("theme", "dark");
var theme = Shiny.Stores.Default.Get<string>("theme");

Available Stores Per Platform

Platform Key Description
Android StoreKeys.Default Preferences
Android StoreKeys.Secure Secure Storage
iOS StoreKeys.Default NSUserDefaults
iOS StoreKeys.Secure Keychain
Windows (packaged) StoreKeys.Default ApplicationData.LocalSettings
Windows (packaged) StoreKeys.Secure Secure Storage (DPAPI)
Windows (unpackaged) StoreKeys.Default JSON file (LocalApplicationData)
Windows (unpackaged) StoreKeys.Secure JSON file + DPAPI encryption
macOS (net10.0-macos) StoreKeys.Default NSUserDefaults
macOS (net10.0-macos) StoreKeys.Secure Keychain
Linux / other desktop StoreKeys.Default JSON file (LocalApplicationData)
Linux / other desktop StoreKeys.Secure JSON file (not encrypted)
WebAssembly StoreKeys.Default localStorage
WebAssembly "session" sessionStorage
All any In-memory dictionary (via MemoryKeyValueStore, great for testing)

Note

For WebAssembly, install the Shiny.Extensions.Stores.Web package and add services.AddShinyWebAssemblyStores() to your service collection.

Note

A dedicated net10.0-macos target gives plain macOS apps NSUserDefaults + Keychain (real secure storage). Other desktop targets that resolve the base net10.0 asset (Linux, and unpackaged Windows) persist both Default and Secure to a JSON file under {LocalApplicationData}/{EntryAssemblyName} so settings survive restarts. Override the location by setting Shiny.Stores.FileStoreDirectory before first access. On these file fallbacks Secure is not encrypted (unpackaged Windows keeps DPAPI over the file) — treat it as obfuscation, not protection, for sensitive data.

Note

On Apple platforms the default store is scoped to the app's own preferences domain. NSUserDefaults.StandardUserDefaults is a search list — it also resolves through the global domain and through defaults any linked framework registered — so Contains/Get deliberately ask the app's persistent domain instead. Without that, an ordinary key name (AutoRecord, UseMetric, Enabled) can read back as present having never been written, and Get(key, defaultValue) would hand back that foreign value instead of your default.

Web Hosting Extensions

  • Merges service container build and post build scenarios into a single class using IWebModule

Setup

  1. Install the NuGet package Shiny.Extensions.WebHosting
  2. Add a web module by implementing IWebModule:
    using Shiny;
    
    public class MyWebModule : IWebModule
    {
        public void Add(WebApplicationBuilder builder)
        {
            // Register your services here
        }
    
        public void Use(WebApplication app)
        {
            // Configure your middleware/endpoints here
        }
    }
  3. In your application hosting startup, add the following:
    using Shiny;
    
    var builder = WebApplication.CreateBuilder(args);
    builder.AddInfrastructureModules(new MyWebModule());
    
    var app = builder.Build();
    app.UseInfrastructureModules();

MAUI Hosting Extensions

  • Module-based MAUI app configuration with IMauiModule
  • Static ShinyHost.Services for accessing the service provider anywhere
  • IAppSupport — device info (manufacturer, model, platform, idiom, OS version), browser/map launch, programmatic orientation lock, and live change events for orientation, culture, and time zone (native listeners on iOS/Android/macOS/Windows, polling fallback elsewhere)
  • IAppStore — cross-platform store version lookups + deep links for the Apple App Store and Mac App Store (iTunes Search API), Google Play (HTML scrape), Microsoft Store (DisplayCatalog API), and Flatpak/Snap on Linux
  • IStartupService — install/remove the app from the desktop OS "launch at login" list (Windows Run key, macOS SMAppService login items on both Mac Catalyst and AppKit, Linux XDG autostart)
  • Desktop backends from dotnet/maui-labs: macOS AppKit (net10.0-macos) is served by this package, Linux GTK4 by the companion Shiny.Extensions.MauiHosting.Linux package
  • Opt-in registration: each capability is its own extension method so apps only pay for what they use

Setup

  1. Install the NuGet package Shiny.Extensions.MauiHosting
  2. Create a MAUI module by implementing IMauiModule:
    using Shiny;
    
    public class MyMauiModule : IMauiModule
    {
        public void Add(MauiAppBuilder builder)
        {
            // Register your services here
        }
    
        public void Use(IPlatformApplication app)
        {
            // Post-build initialization here (do NOT block)
        }
    }
  3. In your MauiProgram.cs:
    using Shiny;
    
    var builder = MauiApp.CreateBuilder();
    builder
        .UseMauiApp<App>()
        .AddInfrastructureModules(new MyMauiModule())   // your IMauiModule list
        .AddAppSupport()                                // IAppSupport
        .AddStartupService()                            // optional: IStartupService (desktop launch at login)
        .AddAppStore(opts =>                            // optional: IAppStore + config
        {
            opts.AppleAppId = "1234567890";
            opts.WindowsProductId = "9NBLGGH4NNS1";
        });
    
    return builder.Build();
  4. Access services anywhere via ShinyHost.Services

IAppSupport

public class MyVm(IAppSupport app)
{
    void Hook()
    {
        // Snapshot
        var version = app.AppVersion;
        var platform = app.Platform;            // "Android", "iOS", "WinUI", "macOS"
        var idiom = app.DeviceIdiom;            // Phone, Tablet, Desktop, …
        var orientation = app.CurrentOrientation;
        var culture = app.CurrentCulture;

        // Live updates
        app.OrientationChanged += (s, e) => { /* new DisplayOrientation */ };
        app.CultureChanged += (s, e) => { /* new CultureInfo */ };
        app.TimeZoneChanged += (s, e) => { /* new TimeZoneInfo */ };

        // Programmatic orientation lock
        _ = app.SetOrientation(DisplayOrientation.Landscape);
        _ = app.ResetOrientation();
    }
}

IStartupService

Installs the app into the operating system's startup (launch at login) list on desktop. Mobile platforms report NotSupported on every call, so the same code is safe to ship in a cross-platform app.

public class StartupToggle(IStartupService startup)
{
    public async Task<string> Toggle(bool runAtLogin)
    {
        if (!startup.IsSupported)
            return "Not a desktop platform";

        var state = runAtLogin
            ? await startup.Register()
            : await startup.Unregister();

        // Enabled | NotRegistered | DisabledByUser | DisabledByPolicy | RequiresApproval
        if (state is StartupServiceState.RequiresApproval or StartupServiceState.DisabledByUser)
            await startup.OpenSettings();   // the user has the final say in the OS UI

        return state.ToString();
    }
}
Platform Mechanism Notes
Windows (unpackaged, WindowsPackageType=None) HKCU\…\CurrentVersion\Run Honours ExecutablePath/Arguments. Reports DisabledByUser when the entry was switched off in Task Manager. OpenSettings opens ms-settings:startupapps
macOS 13+ (Mac Catalyst and AppKit / net10.0-macos) SMAppService.MainApp Registers the running app bundle. First registration commonly returns RequiresApproval until the user approves it in System Settings > General > Login Items, which OpenSettings opens
Linux ~/.config/autostart/{Identifier}.desktop Honours ExecutablePath/Arguments. Reports DisabledByUser when the entry has Hidden=true / X-GNOME-Autostart-enabled=false
Windows (MSIX packaged) Not supported MSIX virtualizes HKCU writes, so a Run entry would be invisible to the shell — packaged apps need a windows.startupTask manifest declaration driven through WinRT. IsSupported reports false
iOS / Android / macOS 12 and earlier Not supported IsSupported is false and every call returns NotSupported
builder.AddStartupService(opts =>
{
    opts.Identifier = "MyApp";                 // Windows Run value name / Linux .desktop file name
    opts.DisplayName = "My App";               // Linux desktop entry name
    opts.Arguments.Add("--autostart");         // Windows + Linux (macOS can't pass arguments)
});

A plain AppKit app with no MauiAppBuilder can register against the service collection instead — the package ships a net10.0-macos asset for exactly this:

services.AddStartupService(opts => opts.Identifier = "MyApp");

IStartupService doesn't touch MAUI Essentials, so it works on the AppKit head with no extra setup. IAppSupport and IAppStore do — see the desktop backend section below.

IAppStore

public class UpdateChecker(IAppStore store)
{
    public async Task Check()
    {
        var result = await store.GetCurrent();
        if (result?.NeedsUpdate == true)
            await store.OpenStore();
    }

    public Task Review() => store.OpenReviewPage();
}
Platform Source of the published version Deep link
iOS / Mac Catalyst iTunes Search API by bundle ID itms-apps://
macOS (AppKit) iTunes Search API by bundle ID, scoped to entity=macSoftware macappstore://
Android Play Store listing scrape market://
Windows Microsoft Store DisplayCatalog API ms-windows-store://
Linux (Shiny.Extensions.MauiHosting.Linux) flatpak remote-info against the remote the app was installed from, or snap info for the tracked channel appstream:// into GNOME Software / Plasma Discover / Snap Store

RequestReview shows the OS's own in-app prompt where one exists (StoreKit on iOS / Mac Catalyst / macOS, StoreContext on Windows). Android and Linux have no dependency-free in-app prompt, so both fall back to OpenReviewPage.

Desktop backends (macOS AppKit + Linux GTK4)

.NET MAUI has no first-party macOS (AppKit) or Linux head. dotnet/maui-labs ships both as experimental preview packages, and this library supports them.

macOS (AppKit)

The net10.0-macos asset of Shiny.Extensions.MauiHosting carries the full surface — IAppSupport, IAppStore, and IStartupService. On that head MAUI Essentials resolves its platform-neutral asset, where every member throws NotImplementedInReferenceAssembly, so the package depends on Microsoft.Maui.Platforms.MacOS.Essentials and AddAppSupport()/AddAppStore() call AddMacOSEssentials() for you.

using Microsoft.Maui.Platforms.MacOS.Hosting;
using Shiny;

var builder = MauiApp.CreateBuilder();
builder
    .UseMauiAppMacOS<App>()
    .AddInfrastructureModules(new MyMauiModule())
    .AddAppSupport()      // wires the AppKit Essentials implementations in
    .AddAppStore(opts => opts.AppleAppId = "1234567890")
    .AddStartupService();

return builder.Build();

Culture and time-zone changes come through NSNotificationCenter, and orientation through DeviceDisplay.MainDisplayInfoChanged (NSApplication.DidChangeScreenParametersNotification). SetOrientation/ResetOrientation return false — AppKit windows don't rotate.

Linux (GTK4)

Linux has no -linux TFM, so a GTK4 head is a plain net10.0 project. The base package's AddAppSupport() would resolve that same throwing Essentials asset, and AddLinuxGtk4Essentials() only redirects five of the static APIs — so Linux gets its own package, Shiny.Extensions.MauiHosting.Linux, whose implementations resolve the Essentials interfaces out of the container instead.

using Microsoft.Maui.Platforms.Linux.Gtk4.Hosting;
using Shiny;

var builder = MauiApp.CreateBuilder();
builder
    .UseMauiAppLinuxGtk4<App>()
    .AddInfrastructureModules(new MyMauiModule())
    .AddLinuxAppSupport()                            // IAppSupport over the GTK4 Essentials services
    .AddLinuxAppStore("org.example.MyApp")           // IAppStore over Flatpak / Snap
    .AddStartupService();                            // XDG autostart, from the base package

return builder.Build();

AddLinuxAppSupport()/AddLinuxAppStore() are named apart from the base AddAppSupport()/AddAppStore() on purpose — both packages put their extensions on MauiAppBuilder in the Shiny namespace, and only one of each pair works on Linux.

Capability Linux behaviour
Device info / browser / map The GTK4 Essentials services (IAppInfo, IDeviceInfo, IBrowser and IMap over xdg-open)
Time zone changes inotify on /etc/localtime, which systemd-timedated replaces on a zone change
Culture changes Polled. A Linux locale switch only takes effect for the next login, so a running process never sees one from the OS
Orientation Reported from the GDK monitor geometry; SetOrientation/ResetOrientation return false
App store flatpak remote-info / snap info. Set AppStoreOptions.LinuxAppId when the app isn't running from a Flatpak or Snap sandbox — there's nothing to auto-detect from

Both backends are 0.1.0-preview packages from dotnet/maui-labs and are not covered by the .NET MAUI support policy. samples/Sample.Maui.MacOS and samples/Sample.Maui.Linux are runnable heads of the shared sample app for each.

Blazor WebAssembly Hosting Extensions

  • IAppSupport for Blazor WebAssembly — app version, browser user-agent (raw string + best-effort parsed browser Version), screen and viewport dimensions, plus live culture / time-zone change events
  • Reads browser state synchronously through IJSInProcessRuntime (same approach as Shiny.Extensions.Stores.Web)

Setup

  1. Install the NuGet package Shiny.Extensions.BlazorHosting
  2. Reference the bundled script in wwwroot/index.html before blazor.webassembly.js:
    <script src="_content/Shiny.Extensions.BlazorHosting/shiny-appsupport.js"></script>
  3. Register at startup, passing the head app's version (no reflection — use the source-generated ThisAssembly):
    using Shiny;
    
    builder.Services.AddAppSupport(ThisAssembly.AssemblyVersion);
  4. Inject IAppSupport anywhere:
    public class MyComponent(IAppSupport app)
    {
        void Hook()
        {
            // Snapshot
            var version = app.AppVersion;
            var ua = app.UserAgent;
            var browser = app.UserAgentVersion;
            var (w, h) = (app.BrowserWidth, app.BrowserHeight);   // viewport — read live
            var (sw, sh) = (app.ScreenWidth, app.ScreenHeight);   // physical screen
    
            // Live updates
            app.CultureChanged += (s, e) => { /* new CultureInfo */ };
            app.TimeZoneChanged += (s, e) => { /* new TimeZoneInfo */ };
        }
    }

Additional Libraries Used

NuGet Packages

Package Description
Shiny.Extensions.DependencyInjection Attribute-driven DI registration with source generators
Shiny.Extensions.Serialization Centralized AOT-safe JSON serializer + [ShinyJsonContext]/[ShinyJsonInclude] source generator
Shiny.Extensions.Stores Cross-platform key/value store abstraction
Shiny.Extensions.Stores.Web Blazor WebAssembly localStorage/sessionStorage
Shiny.Extensions.WebHosting ASP.NET modular web hosting with IWebModule
Shiny.Extensions.MauiHosting MAUI modular hosting with IMauiModule and platform lifecycle hooks (includes the macOS AppKit head)
Shiny.Extensions.MauiHosting.Linux IAppSupport and Flatpak/Snap IAppStore for the MAUI Linux GTK4 backend
Shiny.Extensions.BlazorHosting Blazor WebAssembly IAppSupport — browser/device info and culture/time-zone change events

About

Make .NET Dependency Injection less boilerplatey & Add a pinch of persistent service magic

Topics

Resources

Stars

5 stars

Watchers

0 watching

Forks

Sponsor this project

Used by

Contributors

Languages