{"record":{"id":"779e116b7d4c0541","repo":"RicoSuter/NSwag","slug":"the-nswag-di-services-are-not-registered-call","errorCode":null,"errorMessage":"The NSwag DI services are not registered: Call NSwagServiceCollectionExtensions.AddSwaggerDocument() in ConfigureServices().","messagePattern":"The NSwag DI services are not registered: Call NSwagServiceCollectionExtensions\\.AddSwaggerDocument\\(\\) in ConfigureServices\\(\\)\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/NSwag.AspNetCore/Middlewares/OpenApiDocumentMiddleware.cs","lineNumber":47,"sourceCode":"        private readonly Dictionary<string, Tuple<string, ExceptionDispatchInfo, DateTimeOffset>> _documentsCache = [];\n\n        /// <summary>Initializes a new instance of the <see cref=\"OpenApiDocumentMiddleware\"/> class.</summary>\n        /// <param name=\"nextDelegate\">The next delegate.</param>\n        /// <param name=\"serviceProvider\">The service provider.</param>\n        /// <param name=\"documentName\">The document name.</param>\n        /// <param name=\"path\">The document path.</param>\n        /// <param name=\"settings\">The settings.</param>\n        public OpenApiDocumentMiddleware(RequestDelegate nextDelegate, IServiceProvider serviceProvider, string documentName, string path, OpenApiDocumentMiddlewareSettings settings)\n        {\n            _nextDelegate = nextDelegate;\n\n            _documentName = documentName;\n            _path = path.StartsWith('/') ? path : '/' + path;\n\n            _apiDescriptionGroupCollectionProvider = serviceProvider.GetService<IApiDescriptionGroupCollectionProvider>() ??\n                throw new InvalidOperationException(\"API Explorer not registered in DI.\");\n            _documentProvider = serviceProvider.GetService<OpenApiDocumentProvider>() ??\n                throw new InvalidOperationException(\"The NSwag DI services are not registered: Call \" + nameof(NSwagServiceCollectionExtensions.AddSwaggerDocument) + \"() in ConfigureServices().\");\n\n            _settings = settings;\n        }\n\n        /// <summary>Invokes the specified context.</summary>\n        /// <param name=\"context\">The context.</param>\n        /// <returns>The task.</returns>\n        public async Task Invoke(HttpContext context)\n        {\n            if (context.Request.Path.HasValue && string.Equals(context.Request.Path.Value, _path, StringComparison.OrdinalIgnoreCase))\n            {\n                var schemaJson = await GetDocumentAsync(context);\n                context.Response.StatusCode = 200;\n                context.Response.Headers[\"Content-Type\"] = _path.Contains(\".yaml\", StringComparison.OrdinalIgnoreCase) ?\n                    \"application/yaml; charset=utf-8\" :\n                    \"application/json; charset=utf-8\";\n\n                await context.Response.WriteAsync(schemaJson);","sourceCodeStart":29,"sourceCodeEnd":65,"githubUrl":"https://github.com/RicoSuter/NSwag/blob/63daf8fcc3a25151b62eb4b326a1e8ea048a0d41/src/NSwag.AspNetCore/Middlewares/OpenApiDocumentMiddleware.cs#L29-L65","documentation":"OpenApiDocumentMiddleware requires the NSwag-registered OpenApiDocumentProvider from DI, which is added by NSwagServiceCollectionExtensions.AddSwaggerDocument()/AddOpenApiDocument(). If it is missing, the constructor throws InvalidOperationException telling you to call AddSwaggerDocument() in ConfigureServices().","triggerScenarios":"Calling app.UseOpenApi()/UseSwagger() without first calling services.AddOpenApiDocument()/AddSwaggerDocument(), or registering the middleware in an app that shares no DI container with the one configured.","commonSituations":"Adding only the middleware package without wiring the DI services; moving UseOpenApi to a different host/app builder; forgetting ConfigureServices changes after refactoring.","solutions":["Call services.AddOpenApiDocument() or services.AddSwaggerDocument() in ConfigureServices/builder.Services.","Confirm the middleware is used in the same application whose service provider was configured.","Check package references: NSwag.AspNetCore must be referenced and its DI extension namespace imported (Microsoft.Extensions.DependencyInjection)."],"exampleFix":"// before\nvar app = builder.Build();\napp.UseOpenApi();\n// after\nbuilder.Services.AddOpenApiDocument();\nvar app = builder.Build();\napp.UseOpenApi();","handlingStrategy":"validation","validationCode":"// before UseOpenApi\nif (!builder.Services.Any(d => d.ServiceType == typeof(NSwag.AspNetCore.OpenApiDocumentProvider)))\n    throw new InvalidOperationException(\"Missing AddOpenApiDocument()/AddSwaggerDocument() registration.\");","typeGuard":"bool NswagServicesRegistered(IServiceProvider sp) => sp.GetService<NSwag.AspNetCore.OpenApiDocumentProvider>() != null;","tryCatchPattern":"try { app.UseOpenApi(); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"NSwag DI services are not registered\")) { logger.LogError(ex, \"Add AddSwaggerDocument()/AddOpenApiDocument() in ConfigureServices\"); throw; }","preventionTips":["Always call services.AddOpenApiDocument() or AddSwaggerDocument() before mapping the middleware.","Import Microsoft.Extensions.DependencyInjection so NSwag's service extensions are visible.","Verify registrations with a startup unit test on the built ServiceProvider."],"tags":["aspnetcore","dependency-injection","startup","nswag"],"backgroundTag":"missing-required-config","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"}