Saturday 6 May 2017

Dependency injection in Dot net

What is Dependency Injection? Dependency injection (DI) is a technique by using which we can achieve
  • Loose coupling (decuple) between objects
  • Object's collaborators / dependencies
Dependency injection means giving an object its instance variables. Instead of instantiating a new object as part of another object, we can inject said object when and if it is needed thus removing the first object's dependency on it. It's handy for isolating classes during testing.

  • Constructor Injection 
  • Setter Injection 
  • Interface Injection 

//Constructor Injection
class MovieLister...
public MovieLister(MovieFinder finder) {
this.finder = finder; 

//Setter Injection
class MovieLister...
private MovieFinder finder;
public void setFinder(MovieFinder finder) {
this.finder = finder;

//Interface Injection
public interface InjectFinder {
void injectFinder(MovieFinder finder);

class MovieLister : InjectFinder
public void injectFinder(MovieFinder finder) {
this.finder = finder;


Depth walk through

Simple injector demo in C#

Simple injector offical page

Simple injector Nuget package