When designing an object oriented application, a major concern of design is
"Design must be loosely coupled", which means that objects should have only those
dependencies which are required doing their task and it must be fewer. Object
dependencies should be an interface not on "concrete" objects. Loose coupling
offers us greater reusability, maintainability, and testability.
There are three basic types of Dependency Injection
- Construction Injection
- Setter Injection
- Interface based Injection.
Constructor Injection
The basic idea of constructor-injection is that the object has no defaults or single constructor; instead specified values are required at the time of creation to instantiate the object. In other words Constructor injection uses parameters to inject dependencies.
Advantages
- Construction Injection makes a strong dependency contract
- Construction Injection supports testing, because dependencies can be passed in the constructor.
- A dependency may be made immutable by making the dependency reference final by means that it prevents circular dependency.
Disadvantages
- It requires up front wiring of the entire dependency graph.
The class that needs the Dependency must be
exposing a public constructor that takes dependent class as constructor
argument. In most cases, this should be the only one available constructor but
if more than one Dependency is required then additional constructor
arguments can be used.
Example
In this example "BusinessHelper" class's constructor takes an argument. Dependency
inject from constructor argument.
- public class CommonClass
- {
- //Implement common property and method.
- }
- public class FirstObject : CommonClass
- {
- public string GetData()
- {
- using (var helper = new BusinessHelper(this))
- {
- return helper.GetName();
- }
- }
- }
- public class BusinessHelper : IDisposable
- {
- public BusinessHelper(CommonClass clsCommon) {}
- public string GetName()
- {
- return "Jignesh Test";
- }
- public void Dispose()
- {
- // Dispose your object that out of scoped
- }
- }

Lawrine NicholosPosted May 19, 2017, 5:59 AM
Explained in different way : http://www.fourthbottle.com/2017/05/dependency-injection-in-net-with-ninject.html
Shivprasad Koir KoiralaPosted Sep 2, 2014, 5:07 AM
Nice just recorded a 30 minutes video on DI using unity https://www.youtube.com/watch?v=FuAhnqSDe-o
Umesh PanditPosted Oct 29, 2013, 8:39 AM
Very nice article!!!
Akshay TeotiaPosted Jan 12, 2012, 11:16 AM
Great work.
Arjun PanwarPosted Jan 12, 2012, 11:07 AM
Thanks for sharing
Irshad VazaPosted Jan 12, 2012, 4:38 AM
Very good article........
Abhi KumarPosted Jan 11, 2012, 11:15 PM
Nice article. Thanks for sharing.
Monika AroraPosted Jan 11, 2012, 11:15 PM
Nicely explained article.