{"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/3600ca084e9c8b5f4174fc5e747f4c52d2100806/src/Components/Components/src/OwningComponentBase.cs#L19-L55","documentation":"Thrown by the ScopedServices getter on OwningComponentBase when ScopeFactory (the [Inject]ed IServiceScopeFactory) is still null. OwningComponentBase creates a DI scope on demand, but the factory is only assigned by the components framework during initialization; accessing ScopedServices before that point is invalid.","triggerScenarios":"Reading ScopedServices (or the derived Service property of OwningComponentBase<TService>) from a constructor, a field initializer, or any code that runs before SetParametersAsync/OnInitialized. The [Inject] attributes have not yet been populated at that point, so ScopeFactory is null.","commonSituations":"Constructor of an OwningComponentBase-derived component that resolves a service eagerly; a property initializer that calls ScopedServices; accessing Service in OnParametersSet when the component was never initialized (e.g. used outside the renderer).","solutions":["Move service resolution into OnInitialized, OnInitializedAsync, or later lifecycle methods.","Do not read ScopedServices/Service from constructors or field initializers.","If you must hold a reference, lazily resolve it on first use inside a lifecycle method and cache the result in a field.","Ensure the component is actually rendered by the Blazor renderer (not new'd up manually), so injection runs."],"exampleFix":"// before: resolve in constructor - ScopeFactory is null\npublic class MyComponent : OwningComponentBase\n{\n    private readonly IRepo _repo;\n    public MyComponent() => _repo = ScopedServices.GetRequiredService<IRepo>();\n}\n\n// after: resolve in a lifecycle hook\npublic class MyComponent : OwningComponentBase\n{\n    private IRepo _repo = default!;\n    protected override void OnInitialized() => _repo = ScopedServices.GetRequiredService<IRepo>();\n}","handlingStrategy":"validation","validationCode":"if (ScopeFactory is null) throw new InvalidOperationException(\"Component not initialized; access ScopedServices from OnInitialized.\");","typeGuard":null,"tryCatchPattern":"try { service = ScopedServices.GetRequiredService<T>(); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"component is initialized\"))\n{ /* defer resolution to OnInitialized */ }","preventionTips":["Only read ScopedServices/Service from OnInitializedAsync or later lifecycle hooks.","Do not resolve services in constructors or field initializers of components.","Cache resolved services in fields set during OnInitialized so later code reads fields, not ScopedServices."],"tags":["blazor","dependency-injection","lifecycle","components"],"backgroundTag":null,"analyzedSha":"3600ca084e9c8b5f4174fc5e747f4c52d2100806","analyzedAt":"2026-08-11T16:32:30.678Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}