Skip to content

Dependency injection

Stanislav Molchanovskiy edited this page Jul 17, 2022 · 5 revisions

The NClient.Extensions.DependencyInjection package contains methods for adding clients to the ServiceCollection.
Package contains the AddRestNClient extension methods:

var serviceProvider = new ServiceCollection()
    .AddRestNClient<IMyClient>(host: "http://localhost:8080")
    .BuildServiceProvider();

var client = serviceProvider.GetRequiredService<IMyClient>();

and AddNClientFactory:

var serviceProvider = new ServiceCollection()
    .AddRestNClientFactory()
    .BuildServiceProvider();

var nClientFactory = serviceProvider.GetRequiredService<INClientFactory>();
var client = nClientFactory.Create<IMyClient>(host: "http://localhost:8080");

The IHttpClientFactory will be automatically registered in DI and used. The following dependencies will be used if they are added to the service collection: ILoggerFactory, JsonSerializerOptions.

When adding a client to the collection, you can configure it:

serviceCollection
    .AddRestNClient(implementationFactory: (serviceProvider, builder) => builder
        .For<IMyClient>(host: serviceProvider.GetRequiredService<IMyClientOptions>().Value.Host)
        .WithFullResilience()
        .Build());

In addition, you can configure HttpClient to be used at the transport layer:

serviceCollection
    .AddRestNClient<IMyClient>(host: "http://localhost:8080")
    .ConfigureHttpClient(httpClient =>
    {
        httpClient.MaxResponseContentBufferSize = 1000000;
    });

NClientBuilderOptions and NClientFactoryBuilderOptions

You can set general settings for all clients using NClientBuilderOptions:

var serviceCollection = new ServiceCollection()
    .Configure<NClientFactoryBuilderOptions<HttpRequestMessage, HttpResponseMessage>>(options =>
    {
        options.BuilderActions.Add(builder => builder
            .WithFullResilience());
    });

serviceCollection.AddRestNClient<IMyClient1>(host: "http://localhost:5000");  // Method WithFullResilience will be applied
serviceCollection.AddRestNClient<IMyClient2>(host: "http://localhost:8080");  // Method WithFullResilience will be applied

The method NClientFactoryBuilderOptions works the same way.

Clone this wiki locally