I am trying to resolve dependency that is depending on a parameter value in my operation that I am calling.
I have this WCF service
public class InformationService : IInformationService
{
private readonly IValueProvider _valueProvider;
public InformationService(IValueProvider valueProvider)
{
_valueProvider= valueProvider;
}
public CompanyReportResponse CompanyReport(string option)
{
_valueProvider.Execute(option);
}
}
I have also registered two concrete types for my ValueProvider in my container.
Registry.For<IValueProvider>().Add<ValueProvider1>().Named("No1");
Registry.For<IValueProvider>().Add<ValueProvider2>().Named("No2");
Is it somehow possible to use different Value Provider depending of the value of option?
Ie, when option is "value1" then _valueProvider will use the concrete type ValueProvider1 and when option is "value2” then _valueProvider will use the concrete type ValueProvider2.
I see at least 2 different options.
If the
ValueProvideris only used in that method, you could consider Method Injection. Since at the moment of passing theoptionargument you already know which one is going to be used, you could provide the implementation for IValueProvider to use as an additional argument.The second option is to define a factory to build your ValueProvider, and inject this factory via constructor injection. The factory will have a method for instantiating the correct ValueProvider depending on the
optionargument.