-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Support Keyed Services in MVC #50145
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
Changes from 1 commit
6ba8bbd
faaff42
ff48ead
3092e3e
af49ecd
c45ac39
29a9509
7d20273
b93fe29
397abeb
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
#nullable enable | ||
|
||
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; | ||
using Microsoft.Extensions.DependencyInjection; | ||
|
||
namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders; | ||
|
||
/// <summary> | ||
/// An <see cref="IModelBinder"/> which binds models from the request services when a model | ||
/// has the binding source <see cref="BindingSource.KeyedServices"/>. | ||
/// </summary> | ||
public class KeyedServicesModelBinder : IModelBinder | ||
{ | ||
internal bool IsOptional { get; set; } | ||
|
||
internal object? Key { get; set; } | ||
|
||
/// <inheritdoc /> | ||
public Task BindModelAsync(ModelBindingContext bindingContext) | ||
{ | ||
ArgumentNullException.ThrowIfNull(bindingContext); | ||
|
||
var requestServices = bindingContext.HttpContext.RequestServices as IKeyedServiceProvider; | ||
if (requestServices == null) | ||
{ | ||
bindingContext.Result = ModelBindingResult.Failed(); | ||
return Task.CompletedTask; | ||
} | ||
|
||
var model = IsOptional ? | ||
requestServices.GetKeyedService(bindingContext.ModelType, Key) : | ||
requestServices.GetRequiredKeyedService(bindingContext.ModelType, Key); | ||
|
||
if (model != null) | ||
{ | ||
bindingContext.ValidationState.Add(model, new ValidationStateEntry() { SuppressValidation = true }); | ||
} | ||
|
||
bindingContext.Result = ModelBindingResult.Success(model); | ||
return Task.CompletedTask; | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
#nullable enable | ||
|
||
using System.Reflection; | ||
using Microsoft.Extensions.DependencyInjection; | ||
|
||
namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders; | ||
|
||
/// <summary> | ||
/// An <see cref="IModelBinderProvider"/> for binding from the <see cref="IKeyedServiceProvider"/>. | ||
/// </summary> | ||
public class KeyedServicesModelBinderProvider : IModelBinderProvider | ||
{ | ||
/// <inheritdoc /> | ||
public IModelBinder? GetBinder(ModelBinderProviderContext context) | ||
{ | ||
ArgumentNullException.ThrowIfNull(context); | ||
|
||
if (context.BindingInfo.BindingSource != null && | ||
context.BindingInfo.BindingSource.CanAcceptDataFrom(BindingSource.KeyedServices)) | ||
{ | ||
// IsRequired will be false for a Reference Type | ||
// without a default value in a oblivious nullability context | ||
// however, for services we should treat them as required | ||
var isRequired = context.Metadata.IsRequired || | ||
(context.Metadata.Identity.ParameterInfo?.HasDefaultValue != true && | ||
!context.Metadata.ModelType.IsValueType && | ||
context.Metadata.NullabilityState == NullabilityState.Unknown); | ||
|
||
var attribute = context.Metadata.Identity.ParameterInfo?.GetCustomAttribute<FromKeyedServicesAttribute>(); | ||
|
||
|
||
return new KeyedServicesModelBinder | ||
{ | ||
IsOptional = !isRequired, | ||
Key = attribute?.Key | ||
}; | ||
} | ||
|
||
return null; | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System.Net.Http; | ||
|
||
namespace Microsoft.AspNetCore.Mvc.FunctionalTests; | ||
|
||
public class KeyedServicesTests : IClassFixture<MvcTestFixture<BasicWebSite.StartupWithoutEndpointRouting>> | ||
{ | ||
public KeyedServicesTests(MvcTestFixture<BasicWebSite.StartupWithoutEndpointRouting> fixture) | ||
{ | ||
Client = fixture.CreateDefaultClient(); | ||
} | ||
|
||
public HttpClient Client { get; } | ||
|
||
[Fact] | ||
public async Task ExplicitSingleFromKeyedServiceAttribute() | ||
{ | ||
// Arrange | ||
var okRequest = new HttpRequestMessage(HttpMethod.Get, "/services/GetOk"); | ||
var notokRequest = new HttpRequestMessage(HttpMethod.Get, "/services/GetNotOk"); | ||
|
||
// Act | ||
var okResponse = await Client.SendAsync(okRequest); | ||
var notokResponse = await Client.SendAsync(notokRequest); | ||
|
||
// Assert | ||
Assert.True(okResponse.IsSuccessStatusCode); | ||
Assert.True(notokResponse.IsSuccessStatusCode); | ||
Assert.Equal("OK", await okResponse.Content.ReadAsStringAsync()); | ||
Assert.Equal("NOT OK", await notokResponse.Content.ReadAsStringAsync()); | ||
} | ||
|
||
[Fact] | ||
public async Task ExplicitMultipleFromKeyedServiceAttribute() | ||
{ | ||
// Arrange | ||
var request = new HttpRequestMessage(HttpMethod.Get, "/services/GetBoth"); | ||
|
||
// Act | ||
var response = await Client.SendAsync(request); | ||
|
||
// Assert | ||
Assert.True(response.IsSuccessStatusCode); | ||
Assert.Equal("OK,NOT OK", await response.Content.ReadAsStringAsync()); | ||
|
||
var response2 = await Client.SendAsync(new HttpRequestMessage(HttpMethod.Get, "/services/GetBoth")); | ||
Assert.True(response2.IsSuccessStatusCode); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using Microsoft.AspNetCore.Mvc; | ||
|
||
namespace BasicWebSite; | ||
|
||
[ApiController] | ||
[Route("/services")] | ||
public class CustomServicesApiController : Controller | ||
{ | ||
[HttpGet("GetOk")] | ||
public ActionResult<string> GetOk([FromKeyedServices("ok_service")] ICustomService service) | ||
benjaminpetit marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
return service.Process(); | ||
} | ||
|
||
[HttpGet("GetNotOk")] | ||
public ActionResult<string> GetNotOk([FromKeyedServices("not_ok_service")] ICustomService service) | ||
{ | ||
return service.Process(); | ||
} | ||
|
||
[HttpGet("GetBoth")] | ||
public ActionResult<string> GetBoth( | ||
[FromKeyedServices("ok_service")] ICustomService s1, | ||
[FromKeyedServices("not_ok_service")] ICustomService s2) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do we have any tests for optional and required services when the service is missing? |
||
{ | ||
return $"{s1.Process()},{s2.Process()}"; | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using BasicWebSite.Models; | ||
using Microsoft.AspNetCore.Http.HttpResults; | ||
using Microsoft.AspNetCore.Mvc; | ||
|
||
namespace BasicWebSite; | ||
|
||
public interface ICustomService | ||
{ | ||
string Process(); | ||
} | ||
|
||
public class OkCustomService : ICustomService | ||
{ | ||
public string Process() => "OK"; | ||
public override string ToString() => Process(); | ||
} | ||
|
||
public class BadCustomService : ICustomService | ||
{ | ||
public string Process() => "NOT OK"; | ||
public override string ToString() => Process(); | ||
} |
Uh oh!
There was an error while loading. Please reload this page.