AvaloniaUI/Avalonia · error · InvalidOperationException

Unable to locate '{t}'.

Error message

Unable to locate '{t}'.

What it means

Thrown by LocatorExtensions.GetRequiredService(Type) when the dependency resolver returns null for the requested type. AvaloniaLocator is a minimal service locator; a null result means no registration (ToConstant/ToFunc/ToSingleton/ToTransient) exists for that type in the current scope or its parent scope.

Source

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

    }

    [PrivateApi]
    public interface IAvaloniaDependencyResolver
    {
        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 service first: AvaloniaLocator.CurrentMutable.Bind<IFoo>().ToConstant impl).
  2. If the service is optional, use GetService<T>() (returns null) instead of GetRequiredService.
  3. Verify registration order in AppBuilder or test setup; ensure the call happens after Build()/Initialize().

Example fix

// before
var platform = AvaloniaLocator.Current.GetRequiredService(typeof(IPlatformRenderInterface));

// after
// register in test/headless setup first
AvaloniaLocator.CurrentMutable.Bind<IPlatformRenderInterface>().ToConstant(renderInterface);
var platform = AvaloniaLocator.Current.GetRequiredService(typeof(IPlatformRenderInterface));
Defensive patterns

Strategy: try-catch

Validate before calling

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

Try / catch

object svc;
try { svc = AvaloniaLocator.Current.GetRequiredService(t); }
catch (InvalidOperationException) { svc = CreateFallback(t); }

Prevention

When it happens

Trigger: Calling AvaloniaLocator.Current.GetRequiredService(typeof(IFoo)) before registering IFoo; calling it after EnterScope() was disposed; misspelling the service type.

Common situations: Headless/test environments where platform services weren't registered; accessing a service during static initialization before the locator is configured; version upgrades that renamed a service type.

Related errors


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