0

Haven't done .NET for years, getting back into it.

I would like to know where I perform startup in a class library I am developing. This class library will have several different HttpClients, and I would like to follow the pattern described here to use DI to create them.

Where do I add this code? Does in go in a class?; and how do I call it?

I pasted that directly into Rider and got all sorts of intellisense errors, so no idea what's going on there.

serlingpa
  • 12,024
  • 24
  • 80
  • 130
  • Typically you provide a configuration hook that allows for consumers to provide the http clients, OR you expose `IServiceCollection` extensions that the user would call to register your library into their application. – David L Apr 11 '23 at 18:39

1 Answers1

3

The linked code shows how to use generic host for executable projects, class libraries usually should not care about hosting per se.

For libraries usual approach is to provide a method, usually in namespace like MyLib.Extensions.DependencyInjection which performs all the needed setup and registrations (good practice is to call TryAdd instead of Add{Lifetime}):

namespace MyLib.Extensions.DependencyInjection;
public static class MyLibRegistrationExtensions
{
    // possibly add another parameter to provide/setup the SDK settings
    public static IServiceCollection AddMyLib(this IServiceCollection services)
    {
        // registration goes here
        return services;
    }
}

Also this method can expose action to set the options for the library - public static IServiceCollection AddMyLib(this IServiceCollection services, Action<MyLibOptions> setOptions = null) (for example to have an ability to configure URLs for different environments, though if number of library users is limited you can follow "convention" that corresponding URLs should be just set up in the configuration).

See also:

Guru Stron
  • 102,774
  • 10
  • 95
  • 132