user2229874
user2229874

Reputation: 89

Inject dictionary using dependency injection

i created a function(dictionary) for my project:

private static Dictionary<string, Func<IMessageProcessor>> strategyFactories = new Dictionary<string, Func<IMessageProcessor>>()
    {
        { "T.2.12.0", new Func<IMessageProcessor>(() => new HVPVTParser()) },
        { "T.3.03.0", new Func<IMessageProcessor>(() => new PVTParser()) },
        { "Unknown", new Func<IMessageProcessor>(() => new UnknownParser()) }
    };

As per requirement, I want to get rid of new operator for classes (HVPVTParser, PVTParser and UnknownParser). Can I improve function through dependency injection? During research, I found an option to inject my dictionary. I am unable to understand word 'inject'. Can anyone provide code sample to achieve my goal or any guidelines to solve a problem.

Upvotes: 3

Views: 3647

Answers (1)

D Stanley
D Stanley

Reputation: 152501

Typically you "inject" some sort of service that implements an interface. In your case it would be something like:

public interface IStrategyFactoryService
{
    public Dictionary<string, Func<IMessageProcessor>> Factories {get;}
}

Your class would then have a constructor parameter (if the data is required for the class to function) or a property (if the data is helpful but not required).

Then create classes that implement that interface - a real one for the "live" app and a fake one for testing.

Upvotes: 3

Related Questions