Question

Most of the examples for dependency injection I have seen, the dependencies are injected in constructor. In my situation, I cannot inject the dependency through constructor nor any DI tool. So, I have an interface as parameter to the method. I would like to know if it is a bad approach and what disadvantages it has over constructor injection.

Was it helpful?

Solution

There is nothing wrong with a method-level dependency (i.e. something that is only a dependency for a single method), and there is nothing wrong with passing that dependency as an interface.

OTHER TIPS

This is perfectly acceptable.

Some caveats:

  1. Unless the method is called "Init" it should only be used in that function (very confusing to users of the class otherwise).

  2. Make sure all callers of the function have access to the needed interface (obviously).

There aren't any "disadvantages" I can think of, you are just passing a parameter :)

It's absolutely fine to pass in your dependency to a method, in fact it's one of the allowed/accepted paradigms of Dependency Injection Principle, other's being

Constructor Injection - Where you pass in your dependency via a constructor. The Most widely used paradigm.

Property Injection/Setter Injection - Where you pass in your dependency using a property. Again one of the more widely used paradigm. And,

Method Injection - Where you pass in your dependency using a method.

Now there are certain advantages/disadvantages of using Method Injection. One obvious advantage is that Method Injection is absolutely optional. If you don't need the dependency in a particular instance, just don't call the method that injects the dependency. On the other side while calling some other method of the class that needs to access the dependency, you will need to have a check to make sure the dependency has already been injected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top