{"record":{"id":"0a068664a7ccfb0f","repo":"dotnet/aspnetcore","slug":"persistentcomponentstate-already-initialized","errorCode":null,"errorMessage":"PersistentComponentState already initialized.","messagePattern":"PersistentComponentState already initialized\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Components/Components/src/PersistentComponentState.cs","lineNumber":40,"sourceCode":"    internal PersistentComponentState(\n        IDictionary<string, byte[]> currentState,\n        List<PersistComponentStateRegistration> pauseCallbacks,\n        List<RestoreComponentStateRegistration> restoringCallbacks)\n    {\n        _currentState = currentState;\n        _registeredCallbacks = pauseCallbacks;\n        _registeredRestoringCallbacks = restoringCallbacks;\n    }\n\n    internal bool PersistingState { get; set; }\n\n    internal RestoreContext CurrentContext { get; private set; } = RestoreContext.InitialValue;\n\n    internal void InitializeExistingState(IDictionary<string, byte[]> existingState, RestoreContext context)\n    {\n        if (_existingState != null)\n        {\n            throw new InvalidOperationException(\"PersistentComponentState already initialized.\");\n        }\n        _existingState = existingState ?? throw new ArgumentNullException(nameof(existingState));\n        CurrentContext = context;\n    }\n\n    /// <summary>\n    /// Register a callback to persist the component state when the application is about to be paused.\n    /// Registered callbacks can use this opportunity to persist their state so that it can be retrieved when the application resumes.\n    /// </summary>\n    /// <param name=\"callback\">The callback to invoke when the application is being paused.</param>\n    /// <returns>A subscription that can be used to unregister the callback when disposed.</returns>\n    public PersistingComponentStateSubscription RegisterOnPersisting(Func<Task> callback)\n        => RegisterOnPersisting(callback, null);\n\n    /// <summary>\n    /// Register a callback to persist the component state when the application is about to be paused.\n    /// Registered callbacks can use this opportunity to persist their state so that it can be retrieved when the application resumes.\n    /// </summary>","sourceCodeStart":22,"sourceCodeEnd":58,"githubUrl":"https://github.com/dotnet/aspnetcore/blob/294cab2f9b2e03af6b953820c7ab497c3c8b7ad9/src/Components/Components/src/PersistentComponentState.cs#L22-L58","documentation":"PersistentComponentState.InitializeExistingState throws InvalidOperationException if called twice, because _existingState is already set. The framework initializes persisted state once per prerender/restore cycle; a second call indicates duplicate setup logic.","triggerScenarios":"Custom host calling InitializeExistingState twice; middleware or a custom renderer re-running the persist/restore pipeline on the same instance; DI mis-scoping PersistentComponentState as a singleton that gets reused across requests.","commonSituations":"Custom prerendering setup that invokes initialization in more than one place; tests that reuse the instance across render cycles; framework upgrade changing the initialization call frequency.","solutions":["Call InitializeExistingState exactly once per PersistentComponentState lifetime (per request).","Register PersistentComponentState as scoped, not singleton.","Guard host code against double initialization (check before calling)."],"exampleFix":"// before\nstate.InitializeExistingState(data, ctx);\nstate.InitializeExistingState(data, ctx); // duplicate -> throws\n\n// after\nstate.InitializeExistingState(data, ctx); // single call per request scope","handlingStrategy":"validation","validationCode":"// Host code: call once per scoped instance\nif (_stateInitialized) return;\nstate.InitializeExistingState(data, ctx);\n_stateInitialized = true;","typeGuard":null,"tryCatchPattern":"try { state.InitializeExistingState(data, ctx); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"already initialized\"))\n{ logger.LogDebug(\"PersistentComponentState already initialized\"); }","preventionTips":["Register PersistentComponentState as scoped.","Centralize the InitializeExistingState call in a single host setup path.","Add diagnostics to confirm single invocation per request."],"tags":["blazor","persistent-state","lifecycle","initialization","di"],"analyzedSha":"294cab2f9b2e03af6b953820c7ab497c3c8b7ad9","analyzedAt":"2026-08-06T20:08:02.189Z","schemaVersion":2},"datasetVersion":"2026-08-06T23:17:07.152Z"}