According to SOLID principles a class cannot depend on other classes, dependencies have to be injected. It's simple:
class Foo
{
    public Foo(IBar bar)
    {
        this.bar = bar;
    }
    private IBar bar;
}
interface IBar 
{
}
class Bar: IBar 
{
}
But what if I want my Foo class to be able to create Bar's, not knowing the exact implementation behind IBar? I can think of 4 solutions here, but all of them seem to have drawbacks:
- injecting the type of object and using reflection
- using Generics
- using "Service Locator" and calling the Resolve() method.
- creating a separated factory class and injecting it into Foo:
class Foo
{
    public void DoSmth(IBarCreator barCreator) 
    {
        var newBar = barCreator.CreateBar();
    }
}
interface IBarCreator 
{
    IBar CreateBar();
}
class BarCreator : IBarCreator
{
    public IBar CreateBar()
    {
        return new Bar();
    }
}
Last case seems natural, but BarCreator class has too litle code. So how do you think, which is best?
 
     
     
     
     
     
     
    