dcg
dcg

Reputation: 4219

How to create IServiceCollection from existing one?

Let's say I have some kind of sub App that needs some services registered in the main App plus some specific services of its own. I want to know if there's a better/natural way for doing this (some extension method perhaps?). This is what I've done:

public static IServiceCollection ConfigureServices(this IServiceCollection main)
{
    IServiceCollection sub = new ServiceCollection();
    foreach (var serv in main)
    {
        sub.Add(serv);
    }
    return sub;
}

Thanks.

Upvotes: 4

Views: 2726

Answers (1)

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26635

You can use ConfigureServices method of IWebHostBuilder to inject service collection. And then that instance will be passed to ConfigureServices method of Startup class. And I think that extention method is the way to go. But, in my opinion renaming extension method to AddRange makes sense:

WebHost.CreateDefaultBuilder(args)
        .ConfigureServices(servicesCollection =>
         {
             var mainServiceCollection = ...;
             servicesCollection.AddRange(mainServiceCollection);
         })
        .UseStartup<Startup>();

And here is the extension method which is slightly modified version of yours:

public static IServiceCollection AddRange(this IServiceCollection current, IServiceCollection main)
{
    if(current == null)
    {
        throw ArgumentNullException();
    }

    foreach (var serv in main)
    {
        current.Add(serv);
    }

    return current;
}

Upvotes: 3

Related Questions