Skip to content

Throw when AddOpenApiForJsonApi is called before AddJsonApi #1737

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Errors;
using JsonApiDotNetCore.Middleware;
using JsonApiDotNetCore.OpenApi.Swashbuckle.JsonApiMetadata;
using JsonApiDotNetCore.OpenApi.Swashbuckle.SchemaGenerators;
Expand All @@ -23,6 +24,7 @@ public static class ServiceCollectionExtensions
public static void AddOpenApiForJsonApi(this IServiceCollection services, Action<SwaggerGenOptions>? configureSwaggerGenOptions = null)
{
ArgumentNullException.ThrowIfNull(services);
AssertHasJsonApi(services);

AddCustomApiExplorer(services);
AddCustomSwaggerComponents(services);
Expand All @@ -38,6 +40,14 @@ public static void AddOpenApiForJsonApi(this IServiceCollection services, Action
services.Replace(ServiceDescriptor.Singleton<IJsonApiApplicationBuilderEvents, OpenApiApplicationBuilderEvents>());
}

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<OpenApiEndpointConvention>();
Expand Down
Original file line number Diff line number Diff line change
@@ -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<InvalidConfigurationException>()
.WithMessage("Call 'services.AddJsonApi()' before calling 'services.AddOpenApiForJsonApi()'.");
}
}
Loading