0

I want to add some services in my class library project and I found some ways on Google for this https://mcguirev10.com/2018/01/31/net-core-class-library-dependency-injection.html. However, I don't want to register services in my console app or web app. I want to create a complete solution in the class library, where the user doesn't need to register the service when using the library.

Here is what I have tried:

This is my service class:

public static class ServiceCollectionExtension
{
    public static IServiceCollection AddServices(this IServiceCollection services)
    {
        services.AddSingleton<IClient, Client>();
        return services;
    }
}

and I found the register method on the Internet like this:

public class Program
{
    public static async Task Main(string[] args)
    {
        var services = new ServiceCollection();
        services.AddUsefulService();
    }
}

but I don't want to do it like that.

2
  • 1
    Consider that Microsoft themselves supply many optional libraries and almost all of them expose extensions that you're expected to call from the main application's service registration code. They don't attempt to "automagically" register with the DI system. Why do you think your class library is different? Commented May 15 at 6:52
  • It would be good to get familiar with the topics of Composition Root and DI-Friendly libraries. Big question though is: are you creating a reusable library or simply a class library that is used solely within a single solution?
    – Steven
    Commented May 15 at 7:41

1 Answer 1

1

You could try AutoRegisterDI. Here you can find an article (linked in the library readme) But note that, as commented, usually even microsoft provides an extension method to manually register the dependency like builder.services.AddMyService().

I suggest to just have a single extension method that register all the dependencies for your library.

Not the answer you're looking for? Browse other questions tagged or ask your own question.