Understanding Dependency Injection with C#
An easy guide to learn fundamentals of dependency injection
--
Dependency Injection or DI is a design pattern that allows to delegate the creation of dependent objects to another entity outside the main class. DI allows programs to have loosely coupled classes. Let’s understand this with simple examples.
The following example shows a simple class BusinessLogicLayer,
it provides the necessary operations to get information from database. It creates an object of DataAccessLayer
to access to these operations.
In this above example, BusinessLogicLayer
class depends on DataAccessLayer
class. There are some problems with this approach, classes are tightly coupled : BusinessLogicLayer
class needs to create a concrete object of DataAccessLayer
and manages its lifetime, all changes in DataAccessLayer
can have an impact on BusinessLogicLayer
class, finally BusinessLogicLayer
class can’t be tested independently of DataAccessLayer
class.
To avoid these problems we can use DI pattern.
Dependency Injection Implementation
As I said before, DI is a way to delegate lifetime of dependent objects to another component and inject those objects inside the class that depends on them. There are three ways to inject dependencies :
Constructor Injection
In the constructor injection, the injector (delegated class) creates new instances of dependent objects through its constructor.
In this above example, BusinessLogicLayer
class has a constructor with an abstract type IDataAccess
implemented by DataAccessLayer.
The delegated class InjectorService
creates a concrete object and injects…