Home > database >  AddHttpClient<TClient> with just an interface class?
AddHttpClient<TClient> with just an interface class?

Time:08-16

I want to add a httpclient that used to be done like this:

AddHttpClient<IClassName, ClassName>()

But now, the implementation class is set to an internal class.

AddHttpClient<IClassName> 

The above seems to compile no problem but what is it essentially doing?

How will it know the implementation?

CodePudding user response:

AddHttpClient<IClassName>();

This compiles, however, at runtime it will throw an exception saying that it cannot resolve service for type IClassName.

In order to be able to keep your ClassName internal, and at the same time be able to correctly configure your class, you should have a public Extension method in the project where you have access to ClassName:

public static class ConfigExtensions
{
    public static IServiceCollection AddIClassName(this IServiceCollection services)
    {
        services.AddHttpClient<IClassName, ClassName>();
        return services;
    }
}

Now you can call:

services.AddIClassName();

in your Program.cs/Startup.cs

  • Related