Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Globals vs dependency injection

Tags:

c#

Some people say that it is better to use dependency injection. Why is that?

I think it is better to have few global, easy accessible classes, rather than huge constructors.

Does it influence application speed in any way?

Mix of these two would be probably the best.

like image 883
Neomex Avatar asked Dec 21 '22 22:12

Neomex


2 Answers

The main advantage will be decoupling, which will help with unit testing. This sort of depends entirely on how you code these "easily accessible classes".

The idea is this. A class decouples from implementation (class) dependencies by only having a dependency on the contract (interface). In your live environment you may never provide a new implementing class, but in your test environment you very likely will (be it a handmade stub, or a mocked class from a mocking framework).

Application speed would need profiling, but the use of a framework for DI would likely incur some overhead instead of you talking directly to a singleton that you know about. The important question: is this overhead a problem? Only performance expectations and profiling can tell you that. In my experience, the benefits far outweigh the negligible performance detriment.

like image 147
Adam Houldsworth Avatar answered Jan 04 '23 07:01

Adam Houldsworth


You will probably be using static classes and methods as your Globals. They do not have any performance implication. However, static classes do not lend themselves to testability.

What are the downsides to static methods?

Moreover, once your code becomes tightly coupled to static classes (Globals) you will not be able to replace them with alternate implementations in the future. So Globals may not be good design unless used in very simplistic situations.

Note that static classes and methods are compile time binding where as DI is run time binding. Helps you keep your classes loosely coupled.

like image 24
Unmesh Kondolikar Avatar answered Jan 04 '23 09:01

Unmesh Kondolikar