SlideShare a Scribd company logo
1 of 21
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

Dependency injection presentation
Dependency injection presentationDependency injection presentation
Dependency injection presentationAhasanul Kalam Akib
 
Dependency injection using Google guice
Dependency injection using Google guiceDependency injection using Google guice
Dependency injection using Google guiceAman Verma
 
Dependency injection in CakePHP
Dependency injection in CakePHPDependency injection in CakePHP
Dependency injection in CakePHPmarkstory
 
Docker 101: Introduction to Docker
Docker 101: Introduction to DockerDocker 101: Introduction to Docker
Docker 101: Introduction to DockerDocker, Inc.
 
What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...
What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...
What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...Simplilearn
 
iOS architecture patterns
iOS architecture patternsiOS architecture patterns
iOS architecture patternsallanh0526
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 
What is Dependency Injection in Spring Boot | Edureka
What is Dependency Injection in Spring Boot | EdurekaWhat is Dependency Injection in Spring Boot | Edureka
What is Dependency Injection in Spring Boot | EdurekaEdureka!
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Hitesh-Java
 
Angular 8
Angular 8 Angular 8
Angular 8 Sunil OS
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootJosué Neis
 
Microservices
MicroservicesMicroservices
MicroservicesSmartBear
 

What's hot (20)

Dependency injection presentation
Dependency injection presentationDependency injection presentation
Dependency injection presentation
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Reactjs
Reactjs Reactjs
Reactjs
 
Dependency injection using Google guice
Dependency injection using Google guiceDependency injection using Google guice
Dependency injection using Google guice
 
Dependency injection in CakePHP
Dependency injection in CakePHPDependency injection in CakePHP
Dependency injection in CakePHP
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Springboot Microservices
Springboot MicroservicesSpringboot Microservices
Springboot Microservices
 
NestJS
NestJSNestJS
NestJS
 
Spring boot
Spring bootSpring boot
Spring boot
 
Docker 101: Introduction to Docker
Docker 101: Introduction to DockerDocker 101: Introduction to Docker
Docker 101: Introduction to Docker
 
What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...
What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...
What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...
 
iOS architecture patterns
iOS architecture patternsiOS architecture patterns
iOS architecture patterns
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
What is Dependency Injection in Spring Boot | Edureka
What is Dependency Injection in Spring Boot | EdurekaWhat is Dependency Injection in Spring Boot | Edureka
What is Dependency Injection in Spring Boot | Edureka
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
Its time to React.js
Its time to React.jsIts time to React.js
Its time to React.js
 
Angular 8
Angular 8 Angular 8
Angular 8
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
Microservices
MicroservicesMicroservices
Microservices
 

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 PracticeLars-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 Unityrainynovember12
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented ProgrammingAnumod Kumar
 
Dependency Injection and Inversion Of Control
Dependency Injection and Inversion Of ControlDependency Injection and Inversion Of Control
Dependency Injection and Inversion Of ControlSimone Busoli
 
Dependency Injection & IoC
Dependency Injection & IoCDependency Injection & IoC
Dependency Injection & IoCDennis Loktionov
 
Practical Inversion Of Control
Practical Inversion Of ControlPractical Inversion Of Control
Practical Inversion Of Controlmhinze
 
Inversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionInversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionAndriy Buday
 
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 Controldonnfelker
 
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.3Fabien 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 applicativeMicrosoft
 
Dependency Injection in Laravel
Dependency Injection in LaravelDependency Injection in Laravel
Dependency Injection in LaravelHAO-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 ControlVisualBee.com
 
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 controlEmmet Irish
 
Dependency Injection in .NET
Dependency Injection in .NETDependency Injection in .NET
Dependency Injection in .NETRemik Koczapski
 
Dependency Injection And Ioc Containers
Dependency Injection And Ioc ContainersDependency Injection And Ioc Containers
Dependency Injection And Ioc ContainersTim Murphy
 

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
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
 
Dependency Injection And Ioc Containers
Dependency Injection And Ioc ContainersDependency Injection And Ioc Containers
Dependency Injection And Ioc Containers
 

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 ApplicationTonny 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 functionalMarian Wamsiedel
 
Parsley & Flex
Parsley & FlexParsley & Flex
Parsley & Flexprideconan
 
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 PickinGavin 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 OneAaron 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 FrameworkAkhil Mittal
 
JavaFX for Business Application Developers
JavaFX for Business Application DevelopersJavaFX for Business Application Developers
JavaFX for Business Application DevelopersMichael 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 ContainerDiego Lewin
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfoliomwillmer
 
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 containersJamie 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 2011telestax
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core DataMake 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 applicationsMatteo 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 architectureRomain 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 v2Jamie 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