Home > Enterprise >  How to use IHttpClientFactory in class library
How to use IHttpClientFactory in class library

Time:04-26

I am trying to convert some code from net core api to class library.

I am stuck how to use HttpClientfactory. Normally the httpclientfactory can be configured in program.cs or Startup like

services.AddHttpClient("abc", xxx config). 

How to do configurations in class library for Httpclientfactory.

CodePudding user response:

In your library add an extension method for IServiceCollection to "enable" it in the main project.

In the library:

public static class ServiceCollectionExt
{
    public static void AddYourStaff(this IServiceCollection services)
    {
        services.AddHttpClient("xxx", client =>
        {
            //your staff here
        });
        services.AddSingleton<ISomethingElse, SomethingElse>();
    }
} 

Then in your Startup just call it:

services.AddYourStaff();

UPDATE: As the author described, he's working on the plugin based application. In that case you need some kind of convention, for instance:

  1. each plugin library must have a static class called Registration with the method Invoke(IServiceCollection sc, IConfiguration config)
  2. Then in your Startup you can iterate through all plugin libraries and call their Registration.Invoke(sc, config) using reflection

CodePudding user response:

IHttpClientFactory used in this project

https://github.com/1Gelistirici/UltimateFixtureSystem

  • Related