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:
- each plugin library must have a static class called
Registration
with the methodInvoke(IServiceCollection sc, IConfiguration config)
- Then in your
Startup
you can iterate through all plugin libraries and call theirRegistration.Invoke(sc, config)
using reflection
CodePudding user response:
IHttpClientFactory used in this project