Best practice with many options in the constructor?

If I have a view that needs access to 5 different repositories, I am doing it right now:

public class MyClass { private readonly IRepo1 rep1; private readonly IRepo2 rep2; ... public MyClass(IRepo1 r1, IRepo2 r2, IRepo3 r3, IRepo4 r4...) { rep1 = r1; rep2 = r2; re3 = r3; } } 

The problem with this approach is that the constructor is getting bigger and bigger, and if something changes in the constructor, I have to edit the changes completely through the system. How to avoid this problem?

I thought about creating a builder class that will be responsible for creating the repositories and analyze them in the views. Or is this a bad approach?

+5
source share
2 answers

You can make all your repository interfaces derived from the IRepositoryBase base interface, and then pass the IEnumerable<IRepositoryBase> to your constructor.

In addition, since your repositories end up being processed by MyClass anyway, they probably have some functionality; you can also add methods to IRepositoryBase for this general function, and then MyClass can do its job without having to know the actual types of repositories it is working on.

Code example:

 public class MyClass { private readonly IRepositoryBase[] repos; public MyClass (IEnumerable<IRepositoryBase> r) { repos = r.ToArray(); } // ... } 
-3
source

Instead of using dependency injection (which introduces reflection, making your code slower, insecure, and less readable!), You can use the builder pattern to initialize MyClass instances:

MyClassBuilder.cs

 public class MyClassBuilder { IRepo1 rep1; IRepo2 rep2; IRepo3 rep3; IRepo4 rep4; // ... public MyClassBuilder() { } public MyClassBuilder setRepo1(IRepo1 rep1) { this.rep1 = rep1; return this; } public MyClassBuilder setRepo2(IRepo2 rep1) { this.rep2 = rep2; return this; } public MyClassBuilder setRepo3(IRepo3 rep3) { this.rep3 = rep3; return this; } public MyClassBuilder setRepo4(IRepo4 rep4) { this.rep4 = rep4; return this; } // ... public MyClass build() { return new MyClass( rep1 ?? DEFAULT_REP1, rep2 ?? DEFAULT_REP2, rep3 ?? DEFAULT_REP3, rep4 ?? DEFAULT_REP4 // ... ); } } 

Using an example :

 MyClass myclass = new MyClassBuilder() .setRepo1(new Repo1(/*...*/)) .setRepo4(new Repo4(/*...*/)) .build(); 
-5
source

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


All Articles