zymlabs / nswag-fluentvalidation

Use FluentValidation rules instead of ComponentModel attributes to define swagger schema.
MIT License
60 stars 13 forks source link

Startup setup #1

Open ylbillyli opened 5 years ago

ylbillyli commented 5 years ago

Instead of building ServiceProvider on-the-fly just to resolve FluentValidationSchemaProcessor, I resolve FluentValidationSchemaProcessor during Configure(IApplicationBuilder app) into a private static variable (it is singleton anyway) and then use it in the SchemaProcessors.Add call

geoffreytran commented 5 years ago

Thanks! I was looking at the NSwag extension code and it looks like AddOpenApiDocument passes in IServiceProvider through Action<AspNetCoreOpenApiDocumentGeneratorSettings, IServiceProvider>, so we can just use it directly without having to build the service provider also.

https://github.com/RicoSuter/NSwag/blob/1a6c959bdb41b41f2f534d3e61a311f1cf0de6f7/src/NSwag.AspNetCore/Extensions/NSwagServiceCollectionExtensions.cs#L40

/// <summary>Adds services required for Swagger 2.0 generation (change document settings to generate OpenAPI 3.0).</summary>
/// <param name="serviceCollection">The <see cref="IServiceCollection"/>.</param>
/// <param name="configure">Configure the document.</param>
public static IServiceCollection AddOpenApiDocument(this IServiceCollection serviceCollection, 
    Action<AspNetCoreOpenApiDocumentGeneratorSettings, IServiceProvider> configure = null)`
services.AddOpenApiDocument((document, serviceProvider) =>
{
        var fluentValidationSchemaProcessor = serviceProvider.GetService<FluentValidationSchemaProcessor>();
        document.SchemaProcessors.Add(fluentValidationSchemaProcessor);
});

I'll update the documentation.