AvaloniaUI/Avalonia · error · InvalidOperationException

Unable to locate '{typeof(T)}'.

Error message

Unable to locate '{typeof(T)}'.

What it means

Thrown by the generic LocatorExtensions.GetRequiredService<T> when the resolver has no registration for typeof(T). Identical semantics to [88] but reached via the generic overload; the message includes the full type name of T.

Source

Thrown at src/Avalonia.Base/AvaloniaLocator.cs:140

        object? GetService(Type t);
    }

    [PrivateApi]
    public static class LocatorExtensions
    {
        public static T? GetService<T>(this IAvaloniaDependencyResolver resolver)
        {
            return (T?) resolver.GetService(typeof (T));
        }

        public static object GetRequiredService(this IAvaloniaDependencyResolver resolver, Type t)
        {
            return resolver.GetService(t) ?? throw new InvalidOperationException($"Unable to locate '{t}'.");
        }

        public static T GetRequiredService<T>(this IAvaloniaDependencyResolver resolver)
        {
            return (T?)resolver.GetService(typeof(T)) ?? throw new InvalidOperationException($"Unable to locate '{typeof(T)}'.");
        }
    }
}

View on GitHub (pinned to 11c5427268)

Solutions

  1. Register the type before resolving: AvaloniaLocator.CurrentMutable.Bind<T>().ToSingleton<Impl>().
  2. Use the nullable GetService<T>() when absence is acceptable.
  3. Ensure resolution runs after the platform/app is initialized (e.g. inside a using var app = BuildAvaloniaApp().Setup()) .

Example fix

// before
var clock = AvaloniaLocator.Current.GetRequiredService<IGlobalClock>();

// after
AvaloniaLocator.CurrentMutable.Bind<IGlobalClock>().ToSingleton<GlobalClock>();
var clock = AvaloniaLocator.Current.GetRequiredService<IGlobalClock>();
Defensive patterns

Strategy: try-catch

Validate before calling

var svc = AvaloniaLocator.Current.GetService<T>();
if (svc is null) throw new InvalidOperationException($"Register {typeof(T)} first");

Try / catch

T svc;
try { svc = AvaloniaLocator.Current.GetRequiredService<T>(); }
catch (InvalidOperationException) { svc = Fallback<T>(); }

Prevention

When it happens

Trigger: Calling AvaloniaLocator.Current.GetRequiredService<IFoo>() without prior registration; calling from a background thread or scope where the registration lives only in the root locator.

Common situations: Unit tests missing AppBuilder or locator setup; consuming an internal service that platform code registers lazily; calling a service before the app's compositor/render loop is up.

Related errors


AI-assisted analysis of AvaloniaUI/Avalonia@11c5427268 (2026-08-13). Data as JSON: /api/errors/afaa82831a6c190f. Report an issue: GitHub.