diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ServiceCollectionExtensions.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ServiceCollectionExtensions.cs index 3b421c31d..687211528 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ServiceCollectionExtensions.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ServiceCollectionExtensions.cs @@ -1,4 +1,5 @@ using JsonApiDotNetCore.Configuration; +using JsonApiDotNetCore.Errors; using JsonApiDotNetCore.Middleware; using JsonApiDotNetCore.OpenApi.Swashbuckle.JsonApiMetadata; using JsonApiDotNetCore.OpenApi.Swashbuckle.SchemaGenerators; @@ -23,6 +24,7 @@ public static class ServiceCollectionExtensions public static void AddOpenApiForJsonApi(this IServiceCollection services, Action? configureSwaggerGenOptions = null) { ArgumentNullException.ThrowIfNull(services); + AssertHasJsonApi(services); AddCustomApiExplorer(services); AddCustomSwaggerComponents(services); @@ -38,6 +40,14 @@ public static void AddOpenApiForJsonApi(this IServiceCollection services, Action services.Replace(ServiceDescriptor.Singleton()); } + private static void AssertHasJsonApi(IServiceCollection services) + { + if (services.FirstOrDefault(descriptor => descriptor.ServiceType == typeof(IJsonApiOptions)) == null) + { + throw new InvalidConfigurationException("Call 'services.AddJsonApi()' before calling 'services.AddOpenApiForJsonApi()'."); + } + } + private static void AddCustomApiExplorer(IServiceCollection services) { services.TryAddSingleton(); diff --git a/test/OpenApiTests/OpenApiGenerationFailures/IncorrectSetupOrder/RegistrationTests.cs b/test/OpenApiTests/OpenApiGenerationFailures/IncorrectSetupOrder/RegistrationTests.cs new file mode 100644 index 000000000..603310008 --- /dev/null +++ b/test/OpenApiTests/OpenApiGenerationFailures/IncorrectSetupOrder/RegistrationTests.cs @@ -0,0 +1,24 @@ +using FluentAssertions; +using JsonApiDotNetCore.Errors; +using JsonApiDotNetCore.OpenApi.Swashbuckle; +using Microsoft.Extensions.DependencyInjection; +using Xunit; + +namespace OpenApiTests.OpenApiGenerationFailures.IncorrectSetupOrder; + +public sealed class RegistrationTests +{ + [Fact] + public void Fails_when_OpenAPI_registered_without_JsonApi() + { + // Arrange + var services = new ServiceCollection(); + + // Act + Action action = () => services.AddOpenApiForJsonApi(); + + // Arrange + action.Should().ThrowExactly() + .WithMessage("Call 'services.AddJsonApi()' before calling 'services.AddOpenApiForJsonApi()'."); + } +}