Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency injection in a loop

What is the correct way to do the below so that ParentClass isn't dependant on MyClass?

public class ParentClass
{
    public void MyFunction(IList<Foo> foos)
    {
        foreach (var bar in foos)
        {
            var myClass = new MyClass();
            myClass.DoStuff();
        }
    }
}

Normally without a loop I'd just inject it in with the ParentClass constructor, but here I need a new instance of it for each iteration of the loop.

Or maybe there's a better way altogether to do what I'm trying to achieve? Perhaps myClass could reset itself at the end of each iteration so that I can reuse it?

like image 392
edgarian Avatar asked Mar 15 '12 16:03

edgarian


1 Answers

You can inject a factory object that creates MyClass instances into ParentClass.

For each loop iteration, you call the factory object so it gives you a new instance of MyClass.

like image 164
Fabio Avatar answered Nov 06 '22 19:11

Fabio