openapi-generator icon indicating copy to clipboard operation
openapi-generator copied to clipboard

[REQ] C# - Provide Dependency Injection support

Open CodeRunRepeat opened this issue 11 months ago • 1 comments

Problem

I need to use the generated Client classes through Dependency Injection, including configuration. To achieve this, I would write something like the below for each client, when configuring the service container and repeat the same few lines for each client.

        builder.Services.Configure<Configuration>(builder.Configuration.GetSection(nameof(Configuration)));
        builder.Services.AddSingleton<WeatherForecastApi>((sp) =>
            new WeatherForecastApi(sp.GetRequiredService<IOptions<Configuration>>().Value));

I would prefer to use a simpler way to configure the client, such as

        builder.AddSingletonApiClient<WeatherForecastApi>();

Solution

I propose to introduce a set of generic extensions as part of the Api directory of the C# client that look like this.

CodeRunRepeat avatar Feb 11 '25 13:02 CodeRunRepeat

This is a bit more nuanced than simply just adding singletons.

Ideally, what gets generated by OpenAPI Generator properly wires into using HttpClientFactory

You do not want to just have 1 instance of the httpclient on something like an aspnet app (a common use case)

But you also do not want to spin up an entire new instance for every request.

Instead, you want to properly object pool your http client instances, and luckily the HttpClientFactory provides sane ways to do that.

Ideally the OpenAPI Generator just incorporates itself with that as a solution, and just registers key'd strongly typed HttpClients that you can then just inject into your services.

SteffenBlake avatar May 28 '25 06:05 SteffenBlake