1
+ // Copyright (c) .NET Foundation and contributors. All rights reserved.
2
+
3
+ namespace Microsoft . Extensions . DependencyInjection ;
4
+
5
+ using Asp . Versioning ;
6
+ using Microsoft . AspNetCore . Http ;
7
+
8
+ /// <content>
9
+ /// Provides additional implementation specific to .NET 6.0.
10
+ /// </content>
11
+ public static partial class IServiceCollectionExtensions
12
+ {
13
+ /// <summary>
14
+ /// Enables binding the <see cref="ApiVersion"/> type in Minimal API parameters..
15
+ /// </summary>
16
+ /// <param name="builder">The extended <see cref="IApiVersioningBuilder">API versioning builder</see>.</param>
17
+ /// <returns>The original <paramref name="builder"/>.</returns>
18
+ public static IApiVersioningBuilder EnableApiVersionBinding ( this IApiVersioningBuilder builder )
19
+ {
20
+ if ( builder == null )
21
+ {
22
+ throw new ArgumentNullException ( nameof ( builder ) ) ;
23
+ }
24
+
25
+ // currently required because there is no other hook.
26
+ // 1. TryParse does not work because:
27
+ // a. Parsing is delegated to IApiVersionParser.TryParse
28
+ // b. The result can come from multiple locations
29
+ // c. There can be multiple results
30
+ // 2. BindAsync does not work because:
31
+ // a. It is static and must be on the ApiVersion type
32
+ // b. It is specific to ASP.NET Core
33
+ builder . Services . AddHttpContextAccessor ( ) ;
34
+
35
+ // this registration is 'truthy'. it is possible for the requested API version to be null; however, but the time this is
36
+ // resolved for a request delegate it can only be null if the API is version-neutral and no API version was requested. this
37
+ // should be a rare and nonsensical scenario. declaring the parameter as ApiVersion? should be expect and solve the issue
38
+ //
39
+ // it should also be noted that this registration allows resolving the requested API version from virtually any context.
40
+ // that is not intended, which is why this extension is not named something more general such as AddApiVersionAsService.
41
+ // if/when a better parameter binding mechanism becomes available, this method is expected to become obsolete, no-op, and
42
+ // eventually go away.
43
+ builder . Services . AddTransient ( sp => sp . GetRequiredService < IHttpContextAccessor > ( ) . HttpContext ? . GetRequestedApiVersion ( ) ! ) ;
44
+
45
+ return builder ;
46
+ }
47
+ }
0 commit comments