Tom Boudniatski
Tom Boudniatski

Reputation: 87

How to use Microsoft.Extensions.Http.Polly in netcoreapp3.1 worker service project

I was trying to implement the following article: https://github.com/App-vNext/Polly/wiki/Polly-and-HttpClientFactory

I'm using HttpFactory in my Worker Service project to get some data, I want to make it more robust using Microsoft.Extensions.Http.Polly.

The problem is that I keep getting the following error even though the package is installed :

Error CS0234
The type or namespace name 'Polly' does not exist in the namespace 'Microsoft.Extensions.Http' (are you missing an assembly reference?)

<Project Sdk="Microsoft.NET.Sdk.Worker">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0" />
    <PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" />
    <PackageReference Include="Microsoft.Extensions.Http.Polly" Version="5.0.0" />
    <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\SolutionLibrary\SolutionLibrary.csproj" />
  </ItemGroup>
</Project>

enter image description here

What did I miss ?

Upvotes: 0

Views: 2262

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38795

You're missing that package or assembly name isn't the same as the namespace(s) the code lives in. Although it's often convention that a package named "Foo" will occupy the namespace "Foo" and related namespaces will be something like "Foo.Bar", etc. it's not the only way to do this.

You can find out what namespaces and classes a library makes available to you by using the Object Browser:

  1. In Visual Studio, select "View"
  2. Select "Object Browser"
  3. You will see a list of assemblies that are referenced by your solution
  4. Scroll down to "Microsoft.Extensions.Http.Polly" and expand it

enter image description here

  1. You can see that it declares code in 4 namespaces:
    • Microsoft.Extensions.DependencyInjection
    • Microsoft.Extensions.Http
    • Microsoft.Extensions.Internal
    • Polly

Clicking on "PollyHttpClientBuilderExtensions" shows the methods made available by the class:

enter image description here

And, as the name suggests, the method signature displayed in the lower pane indicates that the selected method is an extension method on IHttpClientBuilder, so you have to use it in conjunction with services.AddHttpClient(). It seems likely that this is the one you want to access in your code. Therefore, you should include the following using:

using Microsoft.Extensions.DependencyInjection;

Upvotes: 2

Related Questions