Search code examples
c#dependency-injectionpolly

Cannot resolve IReadOnlyPolicyRegistry with polly


I have a web api which has all the correct references to polly

One of my services has a constructor with the constructor

public MyService(IReadOnlyPolicyRegistry<string> policyRegistry)

Unable to resolve service for type 'Polly.Registry.IReadOnlyPolicyRegistry`1[System.String]'

How can I fix this? That information is not helpful at all

I am using the Polly packages below

    <PackageReference Include="Polly" Version="7.2.1" />
    <PackageReference Include="Polly.Caching.Distributed" Version="3.0.1" />
    <PackageReference Include="Polly.Caching.Memory" Version="3.0.2" />
    <PackageReference Include="Polly.Contrib.DuplicateRequestCollapser" Version="0.2.1" />

Paul


Solution

  • Polly won't inherently make IReadOnlyPolicyRegistry<string> available to your dependency injection container, so unless you manually add it with its implementation being provided by the PolicyRegistry concrete type, it won't be available.

    However, if you use the Microsoft.Extensions.Http.Polly package in ASP.NET Core with IHttpClientFactory then it will be added automatically by the AddPolicyRegistry() extension method.

    You will need to either add the extra package and then call that method, or manually register the dependency with your service collection, such as by doing:

    services.AddSingleton<IReadOnlyPolicyRegistry<string>, PolicyRegistry>();