Dependency injection for HttpClientFactory with Polly

Mirko Milanovic asked on October 5, 2021 13:07

I need to send HTTP requests with retry policies (with Polly) to an external API from my Kentico Web App, so I need to somehow do the equivalent to this code: //ConfigureServices() - Startup.cs services.AddHttpClient("Name" client => { client.BaseAddress = new Uri("..."); client.DefaultRequestHeaders.Add("..."); }).AddTransientHttpErrorPolicy(...); so I could then be able to use my HttpClient object to send HTTP requests with a retry policy. How can I do this in Kentico?

Recent Answers


Dmitry Bastron answered on October 5, 2021 15:07

Hi Mirko,

Could you provide a bit more info about your case, please?

  • What is the version of CMS you are using?
  • Is it Portal Engine or MVC?
  • Where/when do you need to make these calls? Is it on frontend website, in the CMS admin, scheduled task, etc?
0 votesVote for this answer Mark as a Correct answer

Mirko Milanovic answered on October 5, 2021 15:10 (last edited on October 5, 2021 15:12)

Hi Dmitry,

I am using Kentico 12, it's MVC and I need to make these calls from global Publish and Archive event handlers

0 votesVote for this answer Mark as a Correct answer

Dmitry Bastron answered on October 5, 2021 15:29

Although it's MVC, I think your customization for these events is done in CMS solution (web forms), right?

If that's the case, then there is no proper IoC container there. However, there is a service locator you can use for this I think. Also consider looking through this article about IoC in Kentico, it's not 100% relevant for your case, but you may find some useful bits of code there in DEPENDENCY INJECTION IN THE CMS APP part.

0 votesVote for this answer Mark as a Correct answer

Sean Wright answered on October 7, 2021 17:54

It should be noted that there isn't always an HttpContext available during global events.

Since this customization is happening in global events, if you need the custom module that these events execute from to work in both the Administration and ASPNET Core apps, I'd recommend using RestSharp for HTTP requests, since it works find with .NET Standard 2.0.

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.