In the below example, assume FooA
and FooB
each have constructors that have a large amount of dependencies being injected into them.
If I have a class that needs to determine which IFoo
implementation to use, what is my best method to resolve that? I currently have two possible versions, but I'm not sure either is correct.
public interface IFactory
{
IFoo CreateFoo(bool makeA);
}
public class FactoryA : IFactory
{
private readonly IServiceProvider _services;
public FactoryA(IServiceProvider services)
{
_services = services;
}
public IFoo CreateFoo(bool makeA)
{
if (makeA)
{
return _services.GetRequiredService<FooA>();
}
else
{
return _services.GetRequiredService<FooB>();
}
}
}
public class FactoryB : IFactory
{
private readonly FooA _fooA;
private readonly FooB _fooB;
public FactoryB(FooA fooA, FooB fooB)
{
_fooA = fooA;
_fooB = fooB;
}
public IFoo CreateFoo(bool makeA)
{
if (makeA)
{
return _fooA;
}
else
{
return _fooB;
}
}
}
I feel that FactoryA
is a more correct process, but others at work disagree with passing in IServiceProvider
, however they don't currently have a better recommendation. FactoryB
was the methodology before. My main reason for changing it was complications with testing. I like the clean nature of A vs B and it greatly simplifies unit testing.
In practice an Enum
was being passed in and there was a small switch
statement vs the bool
and if/else
that is currently demo'd.
var factory = serviceProvider.GetRequiredService<IFactory>();
var foo = factory.CreateFoo(false);