How to add Singleton in startup class using Factory method's return value

Viewed 200

I am trying using DI add in my startup class Singleton. I would like to based on processorStringName which comes from appSettings and Factory class add proper processor? Is it possible to do this in a nice way?

 IProcessor processor = ProcessorFactory.CreateProcessor(Configuration, processorStringName);
 services.AddSingleton<IProcessor, processor>();
1 Answers
services.AddSingleton<IProcessor, processor>();

This won't work because processor is a variable name, not a type-name.

Please review the overloads for AddSingleton.

You want this instead:

services.AddSingleton<IProcessor>( implementationInstance: processor );

Or this:

services.AddSingleton<IProcessor>( implementationFactory: sp => processor );
Related