Reputation: 2612
Please checkout the below codes
using Microsoft.Extensions.DependencyInjection;
IServiceProviderFactory<IServiceCollection> serviceProviderFactory =
new DefaultServiceProviderFactory(new ServiceProviderOptions {
ValidateOnBuild = true,
ValidateScopes = true
});
IServiceCollection oldServiceCollection = new ServiceCollection();
IServiceCollection newServiceCollection =
serviceProviderFactory.CreateBuilder(oldServiceCollection);
Assert.IsTrue(oldServiceCollection == newServiceCollection);
I wanted to create a newServiceCollection
base on the oldServiceCollection
(then modify the newServiceCollection
). However (big surprise) the ServiceProviderFactory
, despite being a "Factory" with "Create.." methods, it did not create anything...
The newServiceCollection
IS the oldServiceCollection
. (If I modified the newServiceCollection
then the oldServiceCollection
will be modified as well).
I think that "DefaultServiceProviderFactory" (of Microsoft) is at fault here, do anybody know a better implementation which can help me clone the oldServiceCollection
to make a newServiceCollection
?
Upvotes: 0
Views: 694
Reputation: 172646
This is by design. The DefaultServiceProviderFactory
isn't useful and only exists for other DI Containers to intercept the creation of IServiceCollection
instances.
To make a copy, you'll have to iterate the old collection and add all ServiceDescriptors to the new one:
var newServiceCollection = new ServiceCollection();
foreach (var descriptor in oldServiceCollection)
{
newServiceCollection.Add(descriptor);
}
Upvotes: 2