{"record":{"id":"26dfedad08c8ca0f","repo":"devlooped/moq","slug":"resources-alreadyinitialized","errorCode":null,"errorMessage":"Resources.AlreadyInitialized","messagePattern":"Resources\\.AlreadyInitialized","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/Moq/Mock`1.cs","lineNumber":394,"sourceCode":"        ///   </code>\n        /// </example>\n        public override Mock<TInterface> As<TInterface>()\n        {\n            var interfaceType = typeof(TInterface);\n\n            if (!interfaceType.IsInterface)\n            {\n                throw new ArgumentException(Resources.AsMustBeInterface);\n            }\n\n            if (typeof(TInterface) == typeof(T))\n            {\n                return (Mock<TInterface>)(Mock)this;\n            }\n\n            if (this.IsObjectInitialized && this.ImplementsInterface(interfaceType) == false)\n            {\n                throw new InvalidOperationException(Resources.AlreadyInitialized);\n            }\n\n            if (this.AdditionalInterfaces.Contains(interfaceType) == false)\n            {\n                // We get here for either of two reasons:\n                //\n                // 1. We are being asked to implement an interface that the mocked type does *not* itself\n                //    inherit or implement. We need to hand this interface type to DynamicProxy's\n                //    `CreateClassProxy` method as an additional interface to be implemented.\n                //\n                // 2. The user is possibly going to create a setup through an interface type that the\n                //    mocked type *does* implement. Since the mocked type might implement that interface's\n                //    methods non-virtually, we can only intercept those if DynamicProxy reimplements the\n                //    interface in the generated proxy type. Therefore we do the same as for (1).\n                this.AdditionalInterfaces.Add(interfaceType);\n            }\n\n            return new AsInterface<TInterface>(this);","sourceCodeStart":376,"sourceCodeEnd":412,"githubUrl":"https://github.com/devlooped/moq/blob/89a5be629c752960fe403e95ff583e4ae6f00542/src/Moq/Mock`1.cs#L376-L412","documentation":"Moq throws this InvalidOperationException when As<TInterface>() is called on a mock whose underlying object is already initialized, and the mock does not already implement the requested interface. After the mock object has been created (e.g. after Object was accessed or setups executed), late-adding a brand-new interface would change the type of an already-instantiated object, which is unsafe.","triggerScenarios":"Calling mock.As<INewInterface>() after mock.Object has been materialized, where ImplementsInterface(INewInterface) is false (src/Moq/Mock`1.cs:394).","commonSituations":"Accessing mock.Object early (passing it to SUT setup) and later extending the mock with As<T> in verification code; factory helpers that finalize mocks then callers that extend them.","solutions":["Call As<TInterface>() before first accessing mock.Object or invoking setups.","Check mock.IsObjectInitialized / whether the interface is already implemented before calling As.","Create a new mock including all needed interfaces up front (or via additionalInterfaces at construction)."],"exampleFix":"// before\nvar obj = mock.Object;\nmock.As<IExtra>();\n// after\nmock.As<IExtra>();\nvar obj = mock.Object;","handlingStrategy":"validation","validationCode":"if (mock.IsObjectInitialized && !alreadyImplements)\n    throw new InvalidOperationException(\"Call As<T> before first accessing mock.Object.\");","typeGuard":null,"tryCatchPattern":"try { mock.As<IExtra>(); } catch (InvalidOperationException) { mock = new Mock<T>(); mock.As<IExtra>(); }","preventionTips":["Configure all As<T> interfaces before touching mock.Object","Delay materializing mock.Object until setups are complete","Track mock initialization in factory code"],"tags":["moq","invalid-state","as-interface","lifecycle"],"backgroundTag":"invalid-state-transition","analyzedSha":"89a5be629c752960fe403e95ff583e4ae6f00542","analyzedAt":"2026-09-16T05:31:39.496Z","contentChangedAt":"2026-09-16T05:31:39.496Z","schemaVersion":2},"datasetVersion":"2026-09-16T09:17:16.951Z"}