-2

Let's say I have something like this:

switch(i)  
{  
       case 1: new Class1();break;  
       case 2: new Class2();break;
}

So what's the best practices of doing this if in class where I placed it actively uses DI constructor injection. Is it reasonable to inject all Class1 and Class2 if it ends up with only one implementation?

  • Concrete solution depends on relationship between Class1 and Class2 and where this switch is called. If during app startup or while it is running. – Euphoric Apr 25 '18 at 11:02
2

Your question is unclear as it’s not obvious what happens with those Class1 and Class2 objects. But assuming they are used, do they share an interface? If not, then you are making life hard as far as DI is concerned.

What you should be aiming for is a factory that itself implements an interface. You then inject an instance of that factory interface into the constructor. In turn the factory will have a method that return an instance of the interface that Class1 and Class2 implement.

Your switch statement then resides in a concrete implementation of the factory interface.

EDIT

In light of you comment that a shared interface is used, how this would work goes along the following lines. Let's say you currently have the class Foo:

class Foo
{
    void Bar(int i)
    {
        switch(i)  
        {   
            case 1: DoSomethingWith(new Class1());break;  
            case 2: DoSomethingWith(new Class2());break;
        }
    }

    private void DoSomethingWith(ISomeThing x) ...
}

Then using DI, this might become something like:

class Foo
{
    private readonly ISomethingFactory _factory;

    public Foo(ISomeThingFactory factory) => _factory = factory;

    void Bar(int i) => DoSomethingWith(_factory.CreateObject(i));

    private void DoSomethingWith(ISomeThing x) ...
}

interface ISomethingFactory 
{
    ISomeThing CreateObject(int i);
}

class ConcreteFactory : ISomethingFactory
{
    public ISomeThing CreateObject(int i)
    {
        switch(i)  
        {   
            case 1: return new Class1();  
            case 2: return new Class2();
        }
    }
}

...
var myFoo = new Foo(new ConcreteFactory());
  • Yes, they shared one interface – MrTKer Apr 24 '18 at 21:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.