0

I have a specific scenario where I need to create multiple instances of a class that has dependency injection.

foreach (var setting in settings)
        {
            var client = new ServiceClient();
            dict.Add(somekey, client);
        }

ServiceClient class constructor has implemented DI for other dependent classes. How do I instantiate ServiceClient class?

Faizal
  • 353
  • 3
  • 16
  • 1
    This is a really peculiar requirement. Are you sure you need multiple instances of the `ServiceClient` here? – DavidG Apr 03 '19 at 20:40
  • In addition to DavidG's question, if you determine you DO need multiple instances you could use the Factory pattern and inject the factory into the class: https://en.wikipedia.org/wiki/Factory_method_pattern#C# – Matthew Apr 03 '19 at 20:41
  • @DavidG yes.. need to maintain separate connection instances. – Faizal Apr 03 '19 at 20:47
  • @Matthew not sure how to implement factory pattern here. number instances could vary.. – Faizal Apr 03 '19 at 20:48
  • Do you mean database connections? – DavidG Apr 03 '19 at 20:48
  • @DavidG azure service bus , separate queue connections (number of queues could vary based on configuration settings) – Faizal Apr 03 '19 at 20:51

1 Answers1

0

You could inject a IServiceProvider to get a service with the GetService method "via code".

The service to inject should be transient to get a new Instance each time you request a service from the service provider. If the service to be injected has a scoped lifetime you have to create a new scope around the code to get a new service.

var service = serviceProvider.GetService<IService>();

Consider using a factory method depending on your use case.

Edub
  • 508
  • 7
  • 24