{"record":{"id":"29d3a893ce8d84b4","repo":"dotnet/aspnetcore","slug":"services-cannot-be-accessed-before-the-component-i","errorCode":null,"errorMessage":"Services cannot be accessed before the component is initialized.","messagePattern":"Services cannot be accessed before the component is initialized\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Components/Components/src/OwningComponentBase.cs","lineNumber":37,"sourceCode":"    private AsyncServiceScope? _scope;\n\n    [Inject] IServiceScopeFactory ScopeFactory { get; set; } = default!;\n\n    /// <summary>\n    /// Gets a value determining if the component and associated services have been disposed.\n    /// </summary>\n    protected bool IsDisposed { get; private set; }\n\n    /// <summary>\n    /// Gets the scoped <see cref=\"IServiceProvider\"/> that is associated with this component.\n    /// </summary>\n    protected IServiceProvider ScopedServices\n    {\n        get\n        {\n            if (ScopeFactory == null)\n            {\n                throw new InvalidOperationException(\"Services cannot be accessed before the component is initialized.\");\n            }\n\n            ObjectDisposedException.ThrowIf(IsDisposed, this);\n\n            _scope ??= ScopeFactory.CreateAsyncScope();\n            return _scope.Value.ServiceProvider;\n        }\n    }\n\n    /// <inheritdoc />\n    void IDisposable.Dispose()\n    {\n        Dispose(disposing: true);\n        GC.SuppressFinalize(this);\n    }\n\n    /// <summary>\n    /// Releases the service scope used by the component.","sourceCodeStart":19,"sourceCodeEnd":55,"githubUrl":"https://github.com/dotnet/aspnetcore/blob/294cab2f9b2e03af6b953820c7ab497c3c8b7ad9/src/Components/Components/src/OwningComponentBase.cs#L19-L55","documentation":"OwningComponentBase.ScopedServices throws InvalidOperationException when the injected IServiceScopeFactory (ScopeFactory) is still null, i.e. before Blazor has performed property injection on the component. Accessing ScopedServices (or Service on the generic variant) earlier than OnInitialized is therefore invalid.","triggerScenarios":"Reading ScopedServices from a field initializer or constructor of an OwningComponentBase-derived component; accessing ScopedServices before the renderer injects [Inject] properties; using the component outside the Blazor renderer (manual instantiation).","commonSituations":"Constructor logic that touches ScopedServices; base-class field initializers running before injection; tests that new up the component directly.","solutions":["Defer ScopedServices access to OnInitialized/OnInitializedAsync or later lifecycle methods.","Ensure the component is created by the Blazor renderer (which performs injection), not via new().","In tests, set the ScopeFactory property manually before accessing ScopedServices."],"exampleFix":"// before\npublic class MyComp : OwningComponentBase\n{\n    private readonly Repo _repo = ScopedServices.GetRequiredService<Repo>(); // runs in ctor -> throws\n}\n\n// after\npublic class MyComp : OwningComponentBase\n{\n    private Repo _repo = default!;\n    protected override void OnInitialized() => _repo = ScopedServices.GetRequiredService<Repo>();\n}","handlingStrategy":"validation","validationCode":"protected override void OnInitialized()\n{\n    // Safe to access ScopedServices here; injection has completed\n    _repo = ScopedServices.GetRequiredService<Repo>();\n}","typeGuard":null,"tryCatchPattern":"try { var svc = ScopedServices; }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"before the component is initialized\"))\n{ logger.LogError(ex, \"ScopedServices accessed too early\"); throw; }","preventionTips":["Only touch ScopedServices from OnInitialized onward.","Never new up OwningComponentBase-derived components manually.","In tests, set the ScopeFactory property before access."],"tags":["blazor","component","di","lifecycle","initialization"],"analyzedSha":"294cab2f9b2e03af6b953820c7ab497c3c8b7ad9","analyzedAt":"2026-08-06T20:08:02.189Z","schemaVersion":2},"datasetVersion":"2026-08-06T23:17:07.152Z"}