Manage multiple HttpClient instances using Injection Dependency

I create an instance HttpClientfor each individual API that my web application communicates with.

I want to use Injection Dependency with SimpleInjector to introduce HttpClientinto business classes. For example, I have ITwitterBusinessand IInstagramBusiness, and they both accept HttpClientin their constructor.

What is the best practice for registering multiple objects of the same type using Injection Dependency?

I am sure that my design may be part of the problem, but here are some ideas.

My first idea is to use a delegate in DI registration

container.Register<ITwitterBusiness>(() => new TwitterBusiness(httpClientTwitter));

It seems pretty simple, but I don't know if this method has any bad side effects, for example, if I make SimpleInjector slower or if I break the design pattern.

My second idea is to use context-based injection http://simpleinjector.readthedocs.io/en/latest/advanced.html#context-based-injection

I believe this will allow me to inject a specific instance of HttpClient into a specific class. Still not quite sure how this works.

I am very curious if I can solve this purely by design. For example, creating dummy classes. I simply did not find any good examples, but if I understood it correctly, I could create dummy classes such as HttpClientTwitterthat which inherit HttpClient, and in this way I can get rid of ambiguous registration.

Thank!

+4
1

- DI. , , - , , SimpleInjector .

( ), - , . Simple Injector . , , . HttpClient - , . , , .

, Simple Injector . , - . , .

- . , HttpClient . , .

. :

var httpClientTwitterRegistration = Lifestyle.Transient.CreateRegistration<HttpClient>(
    () => new HttpClient("https://twitter"),
    container);

container.RegisterConditional(typeof(HttpClient), httpClientTwitterRegistration,
    c => c.Consumer.ImplementationType == typeof(TwitterBusiness));

var httpClientInstagramRegistration = Lifestyle.Transient.CreateRegistration<HttpClient>(
    () => new HttpClient("https://instagram"),
    container);

container.RegisterConditional(typeof(HttpClient), httpClientInstagramRegistration,
    c => c.Consumer.ImplementationType == typeof(InstagramBusiness));

,

HttpClient TwitterBusiness, . , swap, HttpClient - , . TwitterBusiness HttpClient, . , HttpContext TwitterBusiness. , (, URL), TwitterBusiness. , TwitterBusiness HttpClient, , (url).

+3

Source: https://habr.com/ru/post/1661347/


All Articles