Skip to content

Commit fe6a129

Browse files
author
Tom Fiedler
committed
use the same instance when a filter implements both sync and async interfaces
1 parent b9e9858 commit fe6a129

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

src/Swashbuckle.AspNetCore.SwaggerGen/DependencyInjection/ConfigureSwaggerGeneratorOptions.cs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ internal class ConfigureSwaggerGeneratorOptions : IConfigureOptions<SwaggerGener
1717
private readonly SwaggerGenOptions _swaggerGenOptions;
1818
private readonly IServiceProvider _serviceProvider;
1919
private readonly IWebHostEnvironment _hostingEnv;
20+
private readonly Dictionary<Type, object> _filterInstances = [];
2021

2122
public ConfigureSwaggerGeneratorOptions(
2223
IOptions<SwaggerGenOptions> swaggerGenOptionsAccessor,
@@ -33,7 +34,7 @@ public void Configure(SwaggerGeneratorOptions options)
3334
DeepCopy(_swaggerGenOptions.SwaggerGeneratorOptions, options);
3435

3536
// Create and add any filters that were specified through the FilterDescriptor lists ...
36-
37+
// if a filter implements both interfaces, the same instance will be used
3738
foreach (var filterDescriptor in _swaggerGenOptions.ParameterFilterDescriptors)
3839
{
3940
if (filterDescriptor.Type.IsAssignableTo(typeof(IParameterFilter)))
@@ -120,8 +121,16 @@ public void DeepCopy(SwaggerGeneratorOptions source, SwaggerGeneratorOptions tar
120121

121122
private TFilter GetOrCreateFilter<TFilter>(FilterDescriptor filterDescriptor)
122123
{
123-
return (TFilter)(filterDescriptor.FilterInstance
124+
if (_filterInstances.TryGetValue(filterDescriptor.Type, out var value))
125+
{
126+
return (TFilter)value;
127+
}
128+
129+
var instance = (TFilter)(filterDescriptor.FilterInstance
124130
?? ActivatorUtilities.CreateInstance(_serviceProvider, filterDescriptor.Type, filterDescriptor.Arguments));
131+
132+
_filterInstances.Add(filterDescriptor.Type, instance);
133+
return instance;
125134
}
126135
}
127136
}

0 commit comments

Comments
 (0)