Reuse model binders (#22391)

* Reuse model binders

Reuse the same model binders for CancellationTokens and services, rather than allocating a new one for every request with such a parameter.
This commit is contained in:
Martin Costello 2020-06-03 21:25:23 +01:00 committed by GitHub
parent 3f83cebeb0
commit 675bceca57
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 10 additions and 2 deletions

View File

@ -11,6 +11,10 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders
/// </summary> /// </summary>
public class CancellationTokenModelBinderProvider : IModelBinderProvider public class CancellationTokenModelBinderProvider : IModelBinderProvider
{ {
// CancellationTokenModelBinder does not have any state. Re-use the same instance for binding.
private readonly CancellationTokenModelBinder _modelBinder = new CancellationTokenModelBinder();
/// <inheritdoc /> /// <inheritdoc />
public IModelBinder GetBinder(ModelBinderProviderContext context) public IModelBinder GetBinder(ModelBinderProviderContext context)
{ {
@ -21,7 +25,7 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders
if (context.Metadata.ModelType == typeof(CancellationToken)) if (context.Metadata.ModelType == typeof(CancellationToken))
{ {
return new CancellationTokenModelBinder(); return _modelBinder;
} }
return null; return null;

View File

@ -10,6 +10,10 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders
/// </summary> /// </summary>
public class ServicesModelBinderProvider : IModelBinderProvider public class ServicesModelBinderProvider : IModelBinderProvider
{ {
// ServicesModelBinder does not have any state. Re-use the same instance for binding.
private readonly ServicesModelBinder _modelBinder = new ServicesModelBinder();
/// <inheritdoc /> /// <inheritdoc />
public IModelBinder GetBinder(ModelBinderProviderContext context) public IModelBinder GetBinder(ModelBinderProviderContext context)
{ {
@ -21,7 +25,7 @@ namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders
if (context.BindingInfo.BindingSource != null && if (context.BindingInfo.BindingSource != null &&
context.BindingInfo.BindingSource.CanAcceptDataFrom(BindingSource.Services)) context.BindingInfo.BindingSource.CanAcceptDataFrom(BindingSource.Services))
{ {
return new ServicesModelBinder(); return _modelBinder;
} }
return null; return null;