Click here to Skip to main content
15,867,704 members
Articles / Programming Languages / C#

Application Architecture - First Know Dependency before Dependency Injection

Rate me:
Please Sign up or sign in to vote.
4.83/5 (22 votes)
23 Apr 2017CPOL7 min read 20.2K   202   25   7
This article is about dependency, type of Dependency, its use, advantages and disadvantages; as well as it will cover Dependency Inversion, Inverse of Control, and IOC Framework.

Dependency Injection

Audience of the Software Design Topics - Developers, Application Architect

What Will You Learn from the Topics

I know you are already familiar with Dependency Inversion (DI) and Inversion of Control (IOC). So, if you already know this, but you are not confident enough to inject dependency into your components; but you want to reuse your components and want to know best design practice for the components, then this article is for you. If you prefer Layers style, N-Tier architecture style, Onion or Daisy architecture style using Domain-Driven-Design or some others, then you may need different implementations of the same type of the components for the same or different applications. So, first know about the dependency, their types and characteristics, then injecting the dependency will be very easy and you will be ready to use Dependency-Inversion principle.

Anyway, the following concepts will be covered in this topic:

  • What is Dependency
  • Type of Dependency
  • Characteristics of the Dependency
  • Use of the dependency in your class design
  • Dependency Inversion
  • In what Scenarios force to use DI
  • What is DI and IOC
  • Type of DI
  • Advantages and disadvantages of DI
  • IOC Framework
  • Use of Munq to your Web application
  • Use of Managed Extensibility Framework (MEF)

Let's Drilldown the Basic Concept

In DI, What's Dependency?

No more theory and definition, let's see the example.

Image 1

In the example:

  • Customer class needs 'CheckingAccount' and 'SavingAccount' classes to do its work.
  • Customer class can't do its work without classes 'CheckingAccount' and 'SavingAccount'.

Image 2

Therefore:

  • Customer Class is a dependent of classes 'CheckingAccount' and 'SavingAccount'.
  • Classes 'CheckingAccount' and 'SavingAccount' are dependency of class Customer

Class Relations of Dependency

  • Two classes (Customer and SavingAccount or CheckingAccount) that use each other are called "coupled".
  • The coupling between classes can be loose or tight or somewhere in between.

Tight Coupling Dependencies

Image 3

In the example, CheckingAccount and SavingingAccount are tightly coupled with the Customer class. This implementation violates the Opened-Closed principles where your classes should be open for extension, but closed for modifications. Anyway, forget the principle. Just think that your checking-account class is fixed in this design and if you need another implantation of the checking-account class, then what should you do?

Loose Coupling Dependencies

Image 4

In the example, the implementation of the interface IBankAccount are CheckingAccount and SavingAccount which are loosely coupled in the customer class. You can inject any different implementation of the IBankAccount into the Customer class.

Direction of Dependency

  • Dependencies or couplings are directional.
  • The Customer depends on CheckingAccount and SavingingAccount, which doesn't mean that CheckingAccount and SavingAccount also depend on Customer.

Characteristics of Dependency

  • Visible Dependencies
  • Hidden Dependencies
  • Direct Dependencies
  • Indirect Dependencies
  • Compile-Time Dependencies
  • Run-Time Dependency

Visible Dependencies

Image 5

In the example, the implementation of the interface IBankAccount are CheckingAccount and SavingingAccount. If you want to create an instance of a customer class, then you can inject any different implementation of the IBankAccount using its constructor. It is visible during object creation.

Image 6

Hidden Dependency

Image 7

Now if you create an object of the Customer class, then you will not get any chance to inject any of the implementation of the IBankAccount Interface. It is hidden during object creation.

Direct Dependency

Image 8

In this example, Customer class uses CheckingAccount and SavingAccount. It means Customer has a direct dependency on CheckingAccount and SavingAccount. So, it is called direct dependency.

Indirect Dependency

Image 9

In the example, CheckingAccount Class has a direct dependency with DataAccessForChecking.

Image 10

So, Customer has a direct dependency with CheckingAccount. Again Checking Account has a direct dependency with DataAccessForChecking. So, Customer class has an indirect dependency with DataAccessForChecking.

To keep it simple, right now, I'm avoiding the compile-time and run-time dependency. Later, I will explain when I will discuss MEF and MUNQ.

Finally, I can say that change the way you think, then you will realize the fact.

Dependency Inversion

Look at the above example where we are considering a layer architecture. I am taking this architecture as an example. Note that Tier and Layer are two different styles. I am ignoring that part as my main goal to show you the DI and IOC.

Image 11

The Presentation Layer(PL) which may contain User Interface Layer(UI) and Presentation Logic Layer(PLL). To make it easy, say we have a web application and the UI means the web-form like *.aspx for ASP.NET or the view like *.cshtml for ASP.NET MVC. PLL means the controller class for the ASP.NET MVC or the *.aspx.cs for ASP.NET.

Business Layer (BL) could be your domain layer. The Data Access Layer (DAL). You can use any ORM like Entity-Framework as a DAL.

Say you have bought some products using any web portal. Now you want to see your order items. So, when you click on a button to display your order, then View will communicate with the controller class. Controller class will call the BL and then BL will call the DAL to verify the customer account information and then finally DAL will send the order information to the BL and BL sends it to the PL to display the order list.

In short, the layers work as follows:

  1. PL depends on BL
  2. BL depends on DAL

So, high level layer depends on the low level layers and these are tight coupling layers. We can't change this dependency at run time or if we have more than one implementation of the DAL or BLL, then what happens? Will we be able to change the way of the dependency from the layers?

Real Life Scenario

Just for easy understanding, let's say, you have a different implementation of the DLL. For example, IDataAccess has two implementations and these are DataAccessForSql and DataAccessForOracle. Depending on customers, sometimes you need DataAccessForSql and sometimes, you need DataAccessForOracle. But tight coupling design will not help you in this scenarios.

Image 12

Again, you have more than one payment system like PayPal, Visa and MasterCard. You need different implementation of your business logics depending on the payment system. For example, say, IPayment has some implementation like PaymentForMasterCard, PaymentForPayPal and PaymentForVisa. So, you need to switch from one to another depends on the preference of the customer. Tight coupling design will not give you these facilities.

Image 13

So the solution is Dependency Inversion.

Principle of the Dependency Inversion

It states that "High-level layers should not depend on low-level layers. Both should depend on abstractions".

Image 14

So we can inject any of the implementation of the DAL to the BL and any of the implementation of BL to the PL.

Image 15

Dependency Injection

Dependency injection is a style of object configuration in which objects are configured by an external entity.

In What Scenarios Do You Need DI

  • Never use DI unless - you don't have control over the lifecycle of the objects.
  • Don't use Container unless something forces you to do that.
  • If you have control to call new to create an object, then you never need DI container.

Type of Dependency Injection

  1. Constructor Injection
  2. Setter Injection
  3. Interface injection

Constructor Injection: Constructor injection uses parameter to inject dependencies.

Image 16

  • Setter Injection: Use setter method to inject the object's dependencies.

Image 17

  • Interface injection: Interface injection is used when an object is defined by an interface and it must be implemented in order to inject dependencies at runtime. So, design an interface to inject dependencies:

Image 18

Disadvantage of DI

  • The guessing that you have decoupled by implementing DI without decoupling it. This is the worse part about DI.

Advantage of DI

  • Unit test or testable code
  • Reuseable code
  • DI helps you with Single Responsibility Principle and Separation of Concerns

DI is Not Effective If

You will never need a:

  • Different implementation
  • Different configuration

Dependency Injection is Effective If

You need to inject:

  • Different implementations of the same dependency
  • The same dependency into multiple components.
  • Configuration data into multiple components
  • The same implementation in different configurations.

Inversion of Control (IoC)

IoC refers to the containers. It is an implementation of using DI which refers to the actual pattern. IoC containers are useful with static dependencies which is used at compile-time and MEF is useful with dynamic dependencies which is used only at run-time.

List of .NET IOC Framework

  • Unity
  • Managed Extensibility Framework(MEF)
  • Munq
  • Funq
  • LightCore
  • Spring .NET
  • Castle Windsor
  • Autofac
  • Structure Map
  • Puzzle.NFactory
  • Ninject
  • S2Container.NET
  • Winter4Net

Which Dependency Injection Tool Should We Use

  • Munq is good for web
  • Unity is good for Enterprise
  • IOC container is best if you want to implement the entire application.
  • If you want to extend only and it is developed by 3rd party, then MEF could be the best.
  • Ninject is too slow container.

Note that there is some philosophical contradiction. But my main goal to give you an idea; so that, you can capture it easily. This is not hard coded rules; so if you have different opinions then you are right too.

History

  • 19th April, 2017: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer
United States United States
Lazy software engineer, don’t believe in hard work.

Comments and Discussions

 
NewsGreat article! Also read my articles on the same topic. Pin
Sudipta Chaudhari14-Jun-18 6:53
Sudipta Chaudhari14-Jun-18 6:53 
PraiseThanks Pin
KennedyKinyanjui23-Apr-17 22:01
KennedyKinyanjui23-Apr-17 22:01 
GeneralRe: Thanks Pin
Habibur Rony24-Apr-17 9:15
Habibur Rony24-Apr-17 9:15 
QuestionDependency Injection Pin
rrotstein21-Apr-17 14:34
rrotstein21-Apr-17 14:34 
AnswerRe: Dependency Injection Pin
Habibur Rony21-Apr-17 16:42
Habibur Rony21-Apr-17 16:42 
GeneralMy vote of 5 Pin
keyur soni19-Apr-17 20:40
keyur soni19-Apr-17 20:40 
GeneralRe: My vote of 5 Pin
Habibur Rony20-Apr-17 11:32
Habibur Rony20-Apr-17 11:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.