SlideShare a Scribd company logo
Inversion of control
         and
Dependency Injection




                    By Dinesh Sharma
   Aware of MVC Framework
   Aware of Web API
   Inversion of Control, or IoC, is an abstract
    principle describing an aspect of some
    software architecture designs in which the
    flow of control of a system is inverted in
    comparison to procedural programming.
   It means, that in procedural programming a
    chunk of code that uses, or consumes,
    another chunk of code is in control of the
    process.
   Dependency Injection is a great way to
    reduce tight coupling between software
    components.
   Instead of hard-coding dependencies, such
    as specifying a database driver, you inject a
    list of services that a component may need.
    The services are then connected by a third
    party.
   This technique enables you to better
    manage future changes and other
    complexity in your software.
   The greatest benefit is that it encourages
    dependency free architecture. Your classes stand
    alone, and do not depend on a specific
    implementation (other than it's interface and
    requirements)
   Flexibility to use alternative implementation of a
    given service without recompiling the application
    code.
   IoC container can control the lifetime of your
    dependencies. Suppose you want an object to exist
    for the lifetime of the request in web page.

                                               Continue
                                               ……
   Code becomes more reusable, testable and
    readable.

   When you test something, if it has a hard coded
    new in there, you can't easily replace it with a
    mocked object to feed it test data. Suppose you
    want to test that an object calculates a value
    correctly. Feeding it test data with known values
    makes it easier to test.
   We can inject
    ◦   Controllers
    ◦   Views
    ◦   Constructors
    ◦   Filters
   Unity (Microsoft Enterprise Library block)
   Ninject
   Castle Windsor
   Autofac
   StructureMap
   Spring.Net
   Etc…….
   We have Products API, which implement the Products
    repository. So we need to create an object of Product
    Repository to access its functionality into API.

    public class EmployeeController : ApiController
        {
            private readonly EmployeeRepository repository;

            public EmployeeController()
            {
                repository = new EmployeeRepository();
    ……………



        Products
                                           Products API
       Repository
   If we create the interface for ProductRepository then we can
    hide our implementation as below   –
    public class ProductsController : ApiController
        {
            private readonly IProductRepository repository;

           public ProductsController()
           {
                  this.repository = new ProductRepository();
           }
                           IEmployee
                           Repository


       Employee
                                           Employee API
       Repository
   In this scenario still we need to look into
    the implementation of ProductRepository.

   How to avoid dependency of
    ProductRepository?

   Let’s inject the Dependency using IoC (Unity)
   Create MVC 4 WebAPI project
   Using NuGet install package for Unity
    ◦ Install-package Unity
   Configure IoC Container (as in coming up
    slides)

   and ready to Go…….
    IoC container implements the Scope container and
     IDependencyResolver interface, which required to implement the
     BeginScope() method as below -

    class IoCContainer : ScopeContainer, IDependencyResolver
       {
           public IoCContainer(IUnityContainer container) : base(container)
           {
           }
           //Creates a nested scope.
           public IDependencyScope BeginScope()
           {
                  var child = container.CreateChildContainer();
               return new ScopeContainer(child);
           }
       }
   Now, Let’s write the ScopeContainer class, which
    implements the IDependencyScope interface.
    IDependencyScope having two methods
    GeteService() and GetServices(),
   These two methods are responsible to create the
    object of dependent class.
class ScopeContainer : IDependencyScope
{
    protected IUnityContainer container;

   public ScopeContainer(IUnityContainer container)
   {
       if (container == null)
       {
           throw new ArgumentNullException("container");
       }
       this.container = container;
   }



                                              Continued…
//Creates one instance of a specified type
public object GetService(Type serviceType)
{
       if container.IsRegistered(serviceType))
     {
              return container.Resolve(serviceType);
       }
       else
     {
              return null;
       }
}


                                                 Continued…
//Create a collection of objects of a specified type
        public IEnumerable<object> GetServices(Type serviceType)
        {
            if (container.IsRegistered(serviceType))
            {
                 return container.ResolveAll(serviceType);
            }
            else
            {
                 return new List<object>();
            }
        }
//Once process is done container dispose the objects
        public void Dispose()
        {
            container.Dispose();
        }
   Let’s create the container and register our
    dependencies to this –

void ConfigureApi(HttpConfiguration config)
{
      var unity = new UnityContainer();
      unity.RegisterType<EmployeeController>();
      unity.RegisterType<IEmployeeRepository,
      EmployeeRepository>(new HierarchicalLifetimeManager());
      config.DependencyResolver = new IoCContainer(unity);
}
Now inject the Dependency, which is
EmployeeRepository here…….

public class EmployeeController : ApiController
    {
        private readonly IEmployeeRepository repository;

       public EmployeeController(IEmployeeRepository repository )
       {
           if (repository == null)
           {
               throw new ArgumentNullException("repository");
           }
           this.repository = repository;
       }
   Download Unity - http://www.microsoft.com/en-in/download/details.aspx?id=17866
   References –
    ◦ http://netmvc.blogspot.in/2012/04/dependency-injection-in-aspnet-mvc-4.html
    ◦ http://haacked.com/archive/2007/12/07/tdd-and-dependency-injection-with-
       asp.net-mvc.aspx
By Dinesh Sharma

More Related Content

What's hot

Clean Architecture
Clean ArchitectureClean Architecture
Clean Architecture
Badoo
 
SOLID Design Principles
SOLID Design PrinciplesSOLID Design Principles
SOLID Design Principles
Andreas Enbohm
 
Dot Net Core
Dot Net CoreDot Net Core
Dot Net Core
Amir Barylko
 
Generics
GenericsGenerics
Generics
Ravi_Kant_Sahu
 
Oop java
Oop javaOop java
Oop java
Minal Maniar
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
Knoldus Inc.
 
Testing with Spring: An Introduction
Testing with Spring: An IntroductionTesting with Spring: An Introduction
Testing with Spring: An Introduction
Sam Brannen
 
Asp.Net Core MVC , Razor page , Entity Framework Core
Asp.Net Core MVC , Razor page , Entity Framework CoreAsp.Net Core MVC , Razor page , Entity Framework Core
Asp.Net Core MVC , Razor page , Entity Framework Core
mohamed elshafey
 
interface in c#
interface in c#interface in c#
interface in c#
Deepti Pillai
 
Flyweight Pattern
Flyweight PatternFlyweight Pattern
Flyweight Pattern
Hüseyin Ergin
 
Collections in-csharp
Collections in-csharpCollections in-csharp
Collections in-csharp
Lakshmi Mareddy
 
Solid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJSSolid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJS
Rafael Casuso Romate
 
Git Tutorial For Beginners | What is Git and GitHub? | DevOps Tools | DevOps ...
Git Tutorial For Beginners | What is Git and GitHub? | DevOps Tools | DevOps ...Git Tutorial For Beginners | What is Git and GitHub? | DevOps Tools | DevOps ...
Git Tutorial For Beginners | What is Git and GitHub? | DevOps Tools | DevOps ...
Simplilearn
 
Introduction to Docker Compose
Introduction to Docker ComposeIntroduction to Docker Compose
Introduction to Docker Compose
Ajeet Singh Raina
 
The aggregate is dead! Long live the aggregate! - SpringIO.pdf
The aggregate is dead! Long live the aggregate! - SpringIO.pdfThe aggregate is dead! Long live the aggregate! - SpringIO.pdf
The aggregate is dead! Long live the aggregate! - SpringIO.pdf
Sara Pellegrini
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
priya_trivedi
 
Generics in java
Generics in javaGenerics in java
Generics in java
suraj pandey
 
Spring Core
Spring CoreSpring Core
Spring Core
Pushan Bhattacharya
 
Developing New Widgets for your Views in Owl
Developing New Widgets for your Views in OwlDeveloping New Widgets for your Views in Owl
Developing New Widgets for your Views in Owl
Odoo
 
Clean architecture on android
Clean architecture on androidClean architecture on android
Clean architecture on android
Benjamin Cheng
 

What's hot (20)

Clean Architecture
Clean ArchitectureClean Architecture
Clean Architecture
 
SOLID Design Principles
SOLID Design PrinciplesSOLID Design Principles
SOLID Design Principles
 
Dot Net Core
Dot Net CoreDot Net Core
Dot Net Core
 
Generics
GenericsGenerics
Generics
 
Oop java
Oop javaOop java
Oop java
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Testing with Spring: An Introduction
Testing with Spring: An IntroductionTesting with Spring: An Introduction
Testing with Spring: An Introduction
 
Asp.Net Core MVC , Razor page , Entity Framework Core
Asp.Net Core MVC , Razor page , Entity Framework CoreAsp.Net Core MVC , Razor page , Entity Framework Core
Asp.Net Core MVC , Razor page , Entity Framework Core
 
interface in c#
interface in c#interface in c#
interface in c#
 
Flyweight Pattern
Flyweight PatternFlyweight Pattern
Flyweight Pattern
 
Collections in-csharp
Collections in-csharpCollections in-csharp
Collections in-csharp
 
Solid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJSSolid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJS
 
Git Tutorial For Beginners | What is Git and GitHub? | DevOps Tools | DevOps ...
Git Tutorial For Beginners | What is Git and GitHub? | DevOps Tools | DevOps ...Git Tutorial For Beginners | What is Git and GitHub? | DevOps Tools | DevOps ...
Git Tutorial For Beginners | What is Git and GitHub? | DevOps Tools | DevOps ...
 
Introduction to Docker Compose
Introduction to Docker ComposeIntroduction to Docker Compose
Introduction to Docker Compose
 
The aggregate is dead! Long live the aggregate! - SpringIO.pdf
The aggregate is dead! Long live the aggregate! - SpringIO.pdfThe aggregate is dead! Long live the aggregate! - SpringIO.pdf
The aggregate is dead! Long live the aggregate! - SpringIO.pdf
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Developing New Widgets for your Views in Owl
Developing New Widgets for your Views in OwlDeveloping New Widgets for your Views in Owl
Developing New Widgets for your Views in Owl
 
Clean architecture on android
Clean architecture on androidClean architecture on android
Clean architecture on android
 

Viewers also liked

Inversion of Control - Introduction and Best Practice
Inversion of Control - Introduction and Best PracticeInversion of Control - Introduction and Best Practice
Inversion of Control - Introduction and Best Practice
Lars-Erik Kindblad
 
Dependency Injection Inversion Of Control And Unity
Dependency Injection Inversion Of Control And UnityDependency Injection Inversion Of Control And Unity
Dependency Injection Inversion Of Control And Unity
rainynovember12
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
Thibaud Desodt
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
Fabien Potencier
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented Programming
Anumod Kumar
 
Dependency Injection and Inversion Of Control
Dependency Injection and Inversion Of ControlDependency Injection and Inversion Of Control
Dependency Injection and Inversion Of Control
Simone Busoli
 
Dependency Injection & IoC
Dependency Injection & IoCDependency Injection & IoC
Dependency Injection & IoC
Dennis Loktionov
 
Practical Inversion Of Control
Practical Inversion Of ControlPractical Inversion Of Control
Practical Inversion Of Control
mhinze
 
Inversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionInversion of Control and Dependency Injection
Inversion of Control and Dependency Injection
Andriy Buday
 
Agile and Frameworks
Agile and FrameworksAgile and Frameworks
Agile and Frameworks
Sander Hoogendoorn
 
Design patterns[observer and ioc]
Design patterns[observer and ioc]Design patterns[observer and ioc]
Design patterns[observer and ioc]
ppdjango
 
20080531 Intro To Dependency Injection & Inversion Of Control
20080531 Intro To Dependency Injection & Inversion Of Control20080531 Intro To Dependency Injection & Inversion Of Control
20080531 Intro To Dependency Injection & Inversion Of Control
donnfelker
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
Fabien Potencier
 
De A à Z : Choisir une architecture pour sa solution applicative
De A à Z : Choisir une architecture pour sa solution applicativeDe A à Z : Choisir une architecture pour sa solution applicative
De A à Z : Choisir une architecture pour sa solution applicative
Microsoft
 
Dependency Injection in Laravel
Dependency Injection in LaravelDependency Injection in Laravel
Dependency Injection in Laravel
HAO-WEN ZHANG
 
The Spring Framework: A brief introduction to Inversion of Control
The Spring Framework:A brief introduction toInversion of ControlThe Spring Framework:A brief introduction toInversion of Control
The Spring Framework: A brief introduction to Inversion of Control
VisualBee.com
 
MVC
MVCMVC
MVC
akshin
 
Functional Dependency Injection in C#
Functional Dependency Injection in C#Functional Dependency Injection in C#
Functional Dependency Injection in C#
Thomas Jaskula
 
Inversion of control
Inversion of controlInversion of control
Inversion of control
Emmet Irish
 
Dependency Injection in .NET
Dependency Injection in .NETDependency Injection in .NET
Dependency Injection in .NET
Remik Koczapski
 

Viewers also liked (20)

Inversion of Control - Introduction and Best Practice
Inversion of Control - Introduction and Best PracticeInversion of Control - Introduction and Best Practice
Inversion of Control - Introduction and Best Practice
 
Dependency Injection Inversion Of Control And Unity
Dependency Injection Inversion Of Control And UnityDependency Injection Inversion Of Control And Unity
Dependency Injection Inversion Of Control And Unity
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented Programming
 
Dependency Injection and Inversion Of Control
Dependency Injection and Inversion Of ControlDependency Injection and Inversion Of Control
Dependency Injection and Inversion Of Control
 
Dependency Injection & IoC
Dependency Injection & IoCDependency Injection & IoC
Dependency Injection & IoC
 
Practical Inversion Of Control
Practical Inversion Of ControlPractical Inversion Of Control
Practical Inversion Of Control
 
Inversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionInversion of Control and Dependency Injection
Inversion of Control and Dependency Injection
 
Agile and Frameworks
Agile and FrameworksAgile and Frameworks
Agile and Frameworks
 
Design patterns[observer and ioc]
Design patterns[observer and ioc]Design patterns[observer and ioc]
Design patterns[observer and ioc]
 
20080531 Intro To Dependency Injection & Inversion Of Control
20080531 Intro To Dependency Injection & Inversion Of Control20080531 Intro To Dependency Injection & Inversion Of Control
20080531 Intro To Dependency Injection & Inversion Of Control
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
 
De A à Z : Choisir une architecture pour sa solution applicative
De A à Z : Choisir une architecture pour sa solution applicativeDe A à Z : Choisir une architecture pour sa solution applicative
De A à Z : Choisir une architecture pour sa solution applicative
 
Dependency Injection in Laravel
Dependency Injection in LaravelDependency Injection in Laravel
Dependency Injection in Laravel
 
The Spring Framework: A brief introduction to Inversion of Control
The Spring Framework:A brief introduction toInversion of ControlThe Spring Framework:A brief introduction toInversion of Control
The Spring Framework: A brief introduction to Inversion of Control
 
MVC
MVCMVC
MVC
 
Functional Dependency Injection in C#
Functional Dependency Injection in C#Functional Dependency Injection in C#
Functional Dependency Injection in C#
 
Inversion of control
Inversion of controlInversion of control
Inversion of control
 
Dependency Injection in .NET
Dependency Injection in .NETDependency Injection in .NET
Dependency Injection in .NET
 

Similar to Inversion of Control and Dependency Injection

L0020 - The Basic RCP Application
L0020 - The Basic RCP ApplicationL0020 - The Basic RCP Application
L0020 - The Basic RCP Application
Tonny Madsen
 
Dependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functionalDependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functional
Marian Wamsiedel
 
Parsley & Flex
Parsley & FlexParsley & Flex
Parsley & Flex
prideconan
 
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Gavin Pickin
 
Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...
Akhil Mittal
 
Appcelerator Titanium Alloy + Kinvey Collection Databinding - Part One
Appcelerator Titanium Alloy + Kinvey Collection Databinding - Part OneAppcelerator Titanium Alloy + Kinvey Collection Databinding - Part One
Appcelerator Titanium Alloy + Kinvey Collection Databinding - Part One
Aaron Saunders
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 
Tdd,Ioc
Tdd,IocTdd,Ioc
DataFX - JavaOne 2013
DataFX - JavaOne 2013DataFX - JavaOne 2013
DataFX - JavaOne 2013
Hendrik Ebbers
 
JavaFX for Business Application Developers
JavaFX for Business Application DevelopersJavaFX for Business Application Developers
JavaFX for Business Application Developers
Michael Heinrichs
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony Container
Diego Lewin
 
Explaination of angular
Explaination of angularExplaination of angular
Explaination of angular
Kan-Han (John) Lu
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
mwillmer
 
Replicating production on your laptop using the magic of containers
Replicating production on your laptop using the magic of containersReplicating production on your laptop using the magic of containers
Replicating production on your laptop using the magic of containers
Jamie Coleman
 
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
telestax
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
Make School
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applications
Matteo Manchi
 
BizSpark SF Lightning Talk: "Automated Testing (Unit, Integration and Systems...
BizSpark SF Lightning Talk: "Automated Testing (Unit, Integration and Systems...BizSpark SF Lightning Talk: "Automated Testing (Unit, Integration and Systems...
BizSpark SF Lightning Talk: "Automated Testing (Unit, Integration and Systems...
Mark A
 
Android application architecture
Android application architectureAndroid application architecture
Android application architecture
Romain Rochegude
 
Replicating production on your laptop using the magic of containers v2
Replicating production on your laptop using the magic of containers v2Replicating production on your laptop using the magic of containers v2
Replicating production on your laptop using the magic of containers v2
Jamie Coleman
 

Similar to Inversion of Control and Dependency Injection (20)

L0020 - The Basic RCP Application
L0020 - The Basic RCP ApplicationL0020 - The Basic RCP Application
L0020 - The Basic RCP Application
 
Dependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functionalDependency injection in Java, from naive to functional
Dependency injection in Java, from naive to functional
 
Parsley & Flex
Parsley & FlexParsley & Flex
Parsley & Flex
 
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin Pickin
 
Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...Inversion of control using dependency injection in Web APIs using Unity Conta...
Inversion of control using dependency injection in Web APIs using Unity Conta...
 
Appcelerator Titanium Alloy + Kinvey Collection Databinding - Part One
Appcelerator Titanium Alloy + Kinvey Collection Databinding - Part OneAppcelerator Titanium Alloy + Kinvey Collection Databinding - Part One
Appcelerator Titanium Alloy + Kinvey Collection Databinding - Part One
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
DataFX - JavaOne 2013
DataFX - JavaOne 2013DataFX - JavaOne 2013
DataFX - JavaOne 2013
 
JavaFX for Business Application Developers
JavaFX for Business Application DevelopersJavaFX for Business Application Developers
JavaFX for Business Application Developers
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony Container
 
Explaination of angular
Explaination of angularExplaination of angular
Explaination of angular
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
Replicating production on your laptop using the magic of containers
Replicating production on your laptop using the magic of containersReplicating production on your laptop using the magic of containers
Replicating production on your laptop using the magic of containers
 
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
 
React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applications
 
BizSpark SF Lightning Talk: "Automated Testing (Unit, Integration and Systems...
BizSpark SF Lightning Talk: "Automated Testing (Unit, Integration and Systems...BizSpark SF Lightning Talk: "Automated Testing (Unit, Integration and Systems...
BizSpark SF Lightning Talk: "Automated Testing (Unit, Integration and Systems...
 
Android application architecture
Android application architectureAndroid application architecture
Android application architecture
 
Replicating production on your laptop using the magic of containers v2
Replicating production on your laptop using the magic of containers v2Replicating production on your laptop using the magic of containers v2
Replicating production on your laptop using the magic of containers v2
 

Inversion of Control and Dependency Injection

  • 1. Inversion of control and Dependency Injection By Dinesh Sharma
  • 2. Aware of MVC Framework  Aware of Web API
  • 3. Inversion of Control, or IoC, is an abstract principle describing an aspect of some software architecture designs in which the flow of control of a system is inverted in comparison to procedural programming.  It means, that in procedural programming a chunk of code that uses, or consumes, another chunk of code is in control of the process.
  • 4. Dependency Injection is a great way to reduce tight coupling between software components.  Instead of hard-coding dependencies, such as specifying a database driver, you inject a list of services that a component may need. The services are then connected by a third party.  This technique enables you to better manage future changes and other complexity in your software.
  • 5. The greatest benefit is that it encourages dependency free architecture. Your classes stand alone, and do not depend on a specific implementation (other than it's interface and requirements)  Flexibility to use alternative implementation of a given service without recompiling the application code.  IoC container can control the lifetime of your dependencies. Suppose you want an object to exist for the lifetime of the request in web page. Continue ……
  • 6. Code becomes more reusable, testable and readable.  When you test something, if it has a hard coded new in there, you can't easily replace it with a mocked object to feed it test data. Suppose you want to test that an object calculates a value correctly. Feeding it test data with known values makes it easier to test.
  • 7. We can inject ◦ Controllers ◦ Views ◦ Constructors ◦ Filters
  • 8. Unity (Microsoft Enterprise Library block)  Ninject  Castle Windsor  Autofac  StructureMap  Spring.Net  Etc…….
  • 9. We have Products API, which implement the Products repository. So we need to create an object of Product Repository to access its functionality into API. public class EmployeeController : ApiController { private readonly EmployeeRepository repository; public EmployeeController() { repository = new EmployeeRepository(); …………… Products Products API Repository
  • 10. If we create the interface for ProductRepository then we can hide our implementation as below – public class ProductsController : ApiController { private readonly IProductRepository repository; public ProductsController() { this.repository = new ProductRepository(); } IEmployee Repository Employee Employee API Repository
  • 11. In this scenario still we need to look into the implementation of ProductRepository.  How to avoid dependency of ProductRepository?  Let’s inject the Dependency using IoC (Unity)
  • 12. Create MVC 4 WebAPI project  Using NuGet install package for Unity ◦ Install-package Unity  Configure IoC Container (as in coming up slides)  and ready to Go…….
  • 13. IoC container implements the Scope container and IDependencyResolver interface, which required to implement the BeginScope() method as below - class IoCContainer : ScopeContainer, IDependencyResolver { public IoCContainer(IUnityContainer container) : base(container) { } //Creates a nested scope. public IDependencyScope BeginScope() { var child = container.CreateChildContainer(); return new ScopeContainer(child); } }
  • 14. Now, Let’s write the ScopeContainer class, which implements the IDependencyScope interface. IDependencyScope having two methods GeteService() and GetServices(),  These two methods are responsible to create the object of dependent class.
  • 15. class ScopeContainer : IDependencyScope { protected IUnityContainer container; public ScopeContainer(IUnityContainer container) { if (container == null) { throw new ArgumentNullException("container"); } this.container = container; } Continued…
  • 16. //Creates one instance of a specified type public object GetService(Type serviceType) { if container.IsRegistered(serviceType)) { return container.Resolve(serviceType); } else { return null; } } Continued…
  • 17. //Create a collection of objects of a specified type public IEnumerable<object> GetServices(Type serviceType) { if (container.IsRegistered(serviceType)) { return container.ResolveAll(serviceType); } else { return new List<object>(); } } //Once process is done container dispose the objects public void Dispose() { container.Dispose(); }
  • 18. Let’s create the container and register our dependencies to this – void ConfigureApi(HttpConfiguration config) { var unity = new UnityContainer(); unity.RegisterType<EmployeeController>(); unity.RegisterType<IEmployeeRepository, EmployeeRepository>(new HierarchicalLifetimeManager()); config.DependencyResolver = new IoCContainer(unity); }
  • 19. Now inject the Dependency, which is EmployeeRepository here……. public class EmployeeController : ApiController { private readonly IEmployeeRepository repository; public EmployeeController(IEmployeeRepository repository ) { if (repository == null) { throw new ArgumentNullException("repository"); } this.repository = repository; }
  • 20. Download Unity - http://www.microsoft.com/en-in/download/details.aspx?id=17866  References – ◦ http://netmvc.blogspot.in/2012/04/dependency-injection-in-aspnet-mvc-4.html ◦ http://haacked.com/archive/2007/12/07/tdd-and-dependency-injection-with- asp.net-mvc.aspx