Loop injection dependency

What is the correct way to do below so that ParentClass not dependent 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 would just enter it using the ParentClass constructor, but here I need a new instance for each iteration of the loop.

Or maybe it's best 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?

+6
source share
4 answers

You can enter a factory object that creates instances of MyClass in the ParentClass.

For each iteration of the loop, you call the factory object to give you a new instance of MyClass.

+7
source

You can inject Func<IMyClass> into the constructor, and then call it as many times as you want to get different instances.

IoC frameworks such as Autofac support this natively.

+1
source

It really depends on what you want to do with MyClass. In its current form, there is no correlation between foo, bar and MyClass. Assuming you have to either enter bar in Ctor MyClass, or pass it as a parameter to DoStuff, then I would just introduce a class or factory method into the ParentClass Ctor and use this instead of the new MyClass.

0
source

The proposed injection is readable, understandable, and easy to verify.

Resetting an object is an option if the loop is large or if MyClass is expensive to create (for example, it opens a connection, file descriptor, subprocess, or starts a thread).

Since the reset() solution takes more time and concentration to check with each code change, I recommend actually measuring that this is a bottleneck before worrying.

0
source

Source: https://habr.com/ru/post/910829/


All Articles