{"record":{"id":"956b58fba0bc9f38","repo":"RicoSuter/NSwag","slug":"unable-to-build-ihost","errorCode":null,"errorMessage":"Unable to build IHost","messagePattern":"Unable to build IHost","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/NSwag.Commands/HostFactoryResolver.cs","lineNumber":255,"sourceCode":"                    {\n                        // Signal that the entry point is completed\n                        _entrypointCompleted?.Invoke(exception);\n                    }\n                })\n                {\n                    // Make sure this doesn't hang the process\n                    IsBackground = true\n                };\n\n                // Start the thread\n                thread.Start();\n\n                try\n                {\n                    // Wait before throwing an exception\n                    if (!_hostTcs.Task.Wait(_waitTimeout))\n                    {\n                        throw new InvalidOperationException(\"Unable to build IHost\");\n                    }\n                }\n                catch (AggregateException) when (_hostTcs.Task.IsCompleted)\n                {\n                    // Lets this propagate out of the call to GetAwaiter().GetResult()\n                }\n\n                Debug.Assert(_hostTcs.Task.IsCompleted);\n\n                return _hostTcs.Task.GetAwaiter().GetResult();\n            }\n\n            public void OnCompleted()\n            {\n                _disposable?.Dispose();\n            }\n\n            public void OnError(Exception error)","sourceCodeStart":237,"sourceCodeEnd":273,"githubUrl":"https://github.com/RicoSuter/NSwag/blob/63daf8fcc3a25151b62eb4b326a1e8ea048a0d41/src/NSwag.Commands/HostFactoryResolver.cs#L237-L273","documentation":"HostFactoryResolver.CreateHost runs the host-building pipeline in a separate process and waits for the built IHost via a task with a timeout (_waitTimeout). If the host isn't built within that time, it throws InvalidOperationException 'Unable to build IHost'. This means the app's host construction hung or crashed before completion.","triggerScenarios":"Running `nswag aspnetcore2openapi /runtime /aspnetcore` where the target app's startup hangs: blocking initialization (database migration at startup, long network calls), a deadlock in Program.cs, slow cold start exceeding the wait timeout, or the host failing to signal completion.","commonSituations":"Apps connecting to a database/Redis at startup in an environment where those services are unreachable; slow CI machines; heavy DI initialization; console logging waits; async void misconfigurations in Program.Main that never complete.","solutions":["Ensure the app's startup completes quickly when run standalone (`dotnet run` and watch for hang); remove blocking startup work.","Make startup dependencies (DB, message broker) available or make their initialization lazy/optional.","Use a newer NSwag version with an increased/adjusted wait timeout for host resolution.","Wrap expensive startup logic behind environment checks (e.g. skip migrations when an env var like NSwag/IsIntegrationTest is set).","Enable app logging (Console/Debug) to see where the host build is stuck."],"exampleFix":"// before: Program.cs blocks on external service at startup\nvar db = new DatabaseMigrator();\ndb.WaitForDatabase(); // hangs when DB unreachable\napp.Run();\n\n// after\ndeferDbMigrations = Environment.GetEnvironmentVariable(\"NSWAG_GENERATION\") == \"1\";\nif (!deferDbMigrations) db.WaitForDatabase();","handlingStrategy":"retry","validationCode":"// sanity-check that the app starts quickly before generation\nvar sw = System.Diagnostics.Stopwatch.StartNew();\nvar p = System.Diagnostics.Process.Start(\"dotnet\", \"run --no-build\");\n// abort if not ready within ~30s\nif (sw.ElapsedMilliseconds > 30000) { p.Kill(); Console.Error.WriteLine(\"App startup hangs; fix blocking startup work.\"); }","typeGuard":null,"tryCatchPattern":"try { GenerateRuntime(project); }\ncatch (InvalidOperationException ex) when (ex.Message == \"Unable to build IHost\") { Console.Error.WriteLine(\"Host build timed out — check for blocking startup dependencies (DB, cache) and retry once services are reachable.\"); }","preventionTips":["Avoid blocking network/DB calls during app startup, or gate them behind an env var","Verify `dotnet run` completes startup quickly in the generation environment","Ensure startup-time services (SQL, Redis) are reachable in CI","Keep NSwag updated — host resolution timeouts have been improved over versions"],"tags":["aspnetcore","hosting","timeout","startup"],"backgroundTag":"request-timeout","analyzedSha":"63daf8fcc3a25151b62eb4b326a1e8ea048a0d41","analyzedAt":"2026-09-14T11:38:15.205Z","contentChangedAt":"2026-09-14T11:38:15.205Z","schemaVersion":2},"datasetVersion":"2026-09-16T09:17:16.951Z"}