I’d be grateful for some advice on avoiding the service locator pattern in a factory of factories. I’m using the LightInject IoC container (because it's fast).
I’d like my factory to return a factory based on the value of an enum, which is passed in as an argument, something like:
public interface IStrategyFactory
{
IMyFactory GetMyFactoryStrategy();
}
public class StrategyFactory : IStrategyFactory
{
public StrategyFactory()
{ }
public IMyFactory GetMyFactoryStrategy(FactoryTypeEnum factoryType)
{
switch (factoryType)
{
case FactoryTypeEnum.Factory1: return container.GetInstance<IMyFactory>("Factory1");
case FactoryTypeEnum.Factory2: return container.GetInstance<IMyFactory>("Factory2");
default: return null;
}
}
}
public interface IMyFactory { }
public class Factory1 : IMyFactory { }
public class Factory2 : IMyFactory { }
Note: the Factory instances have been registered in the IoC container as named instances "Factory1" and "Factory2".
I’m not sure how to get instances of each factory from the IoC container, since that’s not available outside of the application entry point - and I’m not keen on passing the container around the application as I don’t want it as a dependency. Also, I'd rather not inject each factory as that doesn't seem to be that elegant, although it would at least then provide an indication of the factory's dependencies.
Is there a workaround for LightInject? (Hope I don’t have to switch IoC horses!)
Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire