-
Notifications
You must be signed in to change notification settings - Fork 10.4k
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 all commits
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 |
---|---|---|
@@ -1 +1,3 @@ | ||
#nullable enable | ||
Microsoft.AspNetCore.Mvc.ModelBinding.BindingInfo.ServiceKey.get -> object? | ||
Microsoft.AspNetCore.Mvc.ModelBinding.BindingInfo.ServiceKey.set -> void | ||
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. @benjaminpetit here's the modification to the API file that the build is complaining about. Normally we don't change these files in |
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 Microsoft.AspNetCore.Mvc.ModelBinding.Validation; | ||
using Microsoft.Extensions.DependencyInjection; | ||
|
||
namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders; | ||
|
||
internal class KeyedServicesModelBinder : IModelBinder | ||
{ | ||
private readonly object _key; | ||
private readonly bool _isOptional; | ||
|
||
public KeyedServicesModelBinder(object key, bool isOptional) | ||
{ | ||
_key = key ?? throw new ArgumentNullException(nameof(key)); | ||
_isOptional = isOptional; | ||
} | ||
|
||
public Task BindModelAsync(ModelBindingContext bindingContext) | ||
{ | ||
var keyedServices = bindingContext.HttpContext.RequestServices as IKeyedServiceProvider; | ||
benjaminpetit marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if (keyedServices == null) | ||
{ | ||
bindingContext.Result = ModelBindingResult.Failed(); | ||
return Task.CompletedTask; | ||
} | ||
|
||
var model = _isOptional ? | ||
keyedServices.GetKeyedService(bindingContext.ModelType, _key) : | ||
keyedServices.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,89 @@ | ||
// 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()); | ||
} | ||
|
||
[Fact] | ||
public async Task ExplicitSingleFromKeyedServiceAttributeWithNullKey() | ||
{ | ||
// Arrange | ||
var request = new HttpRequestMessage(HttpMethod.Get, "/services/GetKeyNull"); | ||
|
||
// Act | ||
var response = await Client.SendAsync(request); | ||
|
||
// Assert | ||
Assert.True(response.IsSuccessStatusCode); | ||
Assert.Equal("DEFAULT", await response.Content.ReadAsStringAsync()); | ||
} | ||
|
||
[Fact] | ||
public async Task ExplicitSingleFromKeyedServiceAttributeOptionalNotRegistered() | ||
{ | ||
// Arrange | ||
var request = new HttpRequestMessage(HttpMethod.Get, "/services/GetOptionalNotRegistered"); | ||
|
||
// Act | ||
var response = await Client.SendAsync(request); | ||
|
||
// Assert | ||
Assert.True(response.IsSuccessStatusCode); | ||
Assert.Equal(string.Empty, await response.Content.ReadAsStringAsync()); | ||
} | ||
|
||
[Fact] | ||
public async Task ExplicitSingleFromKeyedServiceAttributeRequiredNotRegistered() | ||
{ | ||
// Arrange | ||
var request = new HttpRequestMessage(HttpMethod.Get, "/services/GetRequiredNotRegistered"); | ||
|
||
// Act | ||
var response = await Client.SendAsync(request); | ||
|
||
// Assert | ||
Assert.False(response.IsSuccessStatusCode); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
// 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()}"; | ||
} | ||
|
||
[HttpGet("GetKeyNull")] | ||
public ActionResult<string> GetKeyNull([FromKeyedServices(null)] ICustomService service) | ||
{ | ||
return service.Process(); | ||
} | ||
|
||
# nullable enable | ||
|
||
[HttpGet("GetOptionalNotRegistered")] | ||
public ActionResult<string> GetOptionalNotRegistered([FromKeyedServices("no_existing_key")] ICustomService? service) | ||
{ | ||
if (service != null) | ||
{ | ||
throw new Exception("Service should not have been resolved"); | ||
} | ||
return string.Empty; | ||
} | ||
|
||
[HttpGet("GetRequiredNotRegistered")] | ||
public ActionResult<string> GetRequiredNotRegistered([FromKeyedServices("no_existing_key")] ICustomService service) | ||
{ | ||
return service.Process(); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
// 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(); | ||
} | ||
|
||
public class DefaultCustomService : ICustomService | ||
{ | ||
public string Process() => "DEFAULT"; | ||
public override string ToString() => Process(); | ||
public static DefaultCustomService Instance => new DefaultCustomService(); | ||
} |
Uh oh!
There was an error while loading. Please reload this page.