G
G
Gennady Kruglov2021-08-13 13:01:29
C++ / C#
Gennady Kruglov, 2021-08-13 13:01:29

How to form a collection of services not in the .ConfigureServices() lambda expression, but separately?

Good afternoon.
There is a standard mechanism for creating a host in .NET Core, as well as a standard mechanism for configuring services. It looks something like this:

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((_, services) =>
                    services.AddTransient<ITransientOperation, DefaultOperation>()
                            .AddScoped<IScopedOperation, DefaultOperation>()
                            .AddSingleton<ISingletonOperation, DefaultOperation>()
                            .AddSingleton<IConfigurator, Configurator>()
                            .AddTransient<OperationLogger>());

But, if I want to create a collection of services first, let's say like this:
var serviceCollection = new ServiceCollection(); 
serviceCollection
                .AddSingleton<IConfigurationRoot>(configuration)
                .AddTransient<ITransientOperation, DefaultOperation>()
                .AddScoped<IScopedOperation, DefaultOperation>()
                .AddSingleton<ISingletonOperation, DefaultOperation>()

Then how can I then "slip" it to the host?
hostBuilder.ConfigureServices((_, services) => services = serviceCollection);

That doesn't work.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2021-08-13
@robinzonejob

foreach (var descriptor in serviceCollection)
{
     services.Add(descriptor);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question