Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extending IServiceCollection in asp net core

I want to create a class library project, and in that project include some interfaces and classes that implements those interfaces.

After that, I want to provide this class library project, as a nuget package, so, will be ideal having some kind of extension from IServiceCollection, in order to after the nuget installation, with one line of code in the Startup.cs, ConfigureServices() on the application that is using the nuget, make something like that:

services.AddServicesFromMyNugetPackage()

and that method will be execute, based on IServiceCollection methods, my configuration for DI.

any idea?

like image 353
dennitorf Avatar asked Oct 21 '25 04:10

dennitorf


1 Answers

In your library, you can create a static class and write some extensions methods where you can register your dependencies as the following example:

public static class ServicesExtensions
{
        public static void AddMyLibraryServices(this IServiceCollection services)
        {
            // register your services here
        }
 }

and then in your startup file:

services.AddMyLibraryServices();
like image 97
Getson Cela Avatar answered Oct 24 '25 06:10

Getson Cela



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!