Daryl Young
Daryl Young

Reputation: 394

Dependency Injection - accessing classes in same layer

How does one class use another class in the same layer if both classes have dependencies that are injected via the constructor? Neither one can be considered a cross-cutting concern. Example:

Layer 1:

RepoA, RepoB

Layer 2:

Class1 depends on RepoA

Class2 depends on RepoB, but also needs to call method(s) in Class1

Layer 3:

Controller1 depends on Class1, Class2

Is there a fundamental flaw with this and there should be no situation where Class2 requires Class1? Or does Class2 need to be injected with RepoA so that it can instantiate Class1 when it needs it?

Also, it is possible to inject Class1 into Class2, but that must be the wrong way. It can't possibly make sense to inject a class into another class in the same layer (?).

Upvotes: 1

Views: 190

Answers (2)

Brad Christie
Brad Christie

Reputation: 101614

If you follow the Onion Architecture, it's allowable to [create dependencies on] anything on the same layer and inwards, but never higher. Having said that, you could effectively add Class1 as a dependency to Class2.

As far as my own 2 cents, if this is an implementation that needs to be accessed more commonly, consider (if it makes sense to) adding it to your core contract. Then Class2 could access IClass1.Method.

Upvotes: 0

Sam Holder
Sam Holder

Reputation: 32936

It can't possibly make sense to inject a class into another class in the same layer.

Why? This seems like the solution to me... If Class2 has a dependency on RepoB and Class1 then it should show that by declaring those dependencies in the constructor so that they can be injected. Why does it matter that they are from the same layer?

Upvotes: 1

Related Questions