11using JsonApiDotNetCore . Middleware ;
22using Microsoft . AspNetCore . Builder ;
33using Microsoft . Extensions . DependencyInjection ;
4+ using Microsoft . Extensions . Options ;
45
56namespace JsonApiDotNetCore . Configuration ;
67
@@ -23,6 +24,7 @@ public static class ApplicationBuilderExtensions
2324 public static void UseJsonApi ( this IApplicationBuilder builder )
2425 {
2526 ArgumentNullException . ThrowIfNull ( builder ) ;
27+ AssertAspNetCoreOpenApiIsNotRegistered ( builder . ApplicationServices ) ;
2628
2729 using ( IServiceScope scope = builder . ApplicationServices . CreateScope ( ) )
2830 {
@@ -46,4 +48,33 @@ public static void UseJsonApi(this IApplicationBuilder builder)
4648
4749 builder . UseMiddleware < JsonApiMiddleware > ( ) ;
4850 }
51+
52+ private static void AssertAspNetCoreOpenApiIsNotRegistered ( IServiceProvider serviceProvider )
53+ {
54+ Type ? optionsType = TryLoadOptionsType ( ) ;
55+
56+ if ( optionsType != null )
57+ {
58+ Type configureType = typeof ( IConfigureOptions < > ) . MakeGenericType ( optionsType ) ;
59+ object ? configureInstance = serviceProvider . GetService ( configureType ) ;
60+
61+ if ( configureInstance != null )
62+ {
63+ throw new InvalidOperationException ( "JsonApiDotNetCore is incompatible with ASP.NET OpenAPI. " +
64+ "Replace 'services.AddOpenApi()' with 'services.AddOpenApiForJsonApi()' from the JsonApiDotNetCore.OpenApi.Swashbuckle NuGet package." ) ;
65+ }
66+ }
67+ }
68+
69+ private static Type ? TryLoadOptionsType ( )
70+ {
71+ try
72+ {
73+ return Type . GetType ( "Microsoft.AspNetCore.OpenApi.OpenApiOptions, Microsoft.AspNetCore.OpenApi" ) ;
74+ }
75+ catch ( FileLoadException )
76+ {
77+ return null ;
78+ }
79+ }
4980}
0 commit comments