Published: 21 Sep 2010
By: Brian Mains

How to use Dependency Injection containers in ASP.NET MVC.

Contents [hide]

The ASP.NET MVC 2 Series

  • Introduction to ASP.NET MVC 2.0 In this article, we'll begin examining the new features of ASP.NET MVC 2.0 by comparing what ASP.NET MVC offers against its predecessor, ASP.NET web forms.
  • ASP.NET MVC 2.0 User Interfaces The next part to this article series on MVC 2.0 is the user interface. We saw in the last article some basics on the changes of the user interface, which we'll delve into more in this article series. Here we will begin to look at how developers can construct the view user interface.
  • ASP.NET MVC 2.0 Using Multiple Actions Brian Mains explains how to use multiple actions in ASP.NET MVC 2.0.
  • ASP.NET MVC 2.0 Templating Templating is now in the ASP.NET MVC 2.0 framework, for .NET framework 3.5 and 4.0. We are going to take a look at these features.
  • ASP.NET MVC 2.0 Attributes An overview of ASP.NET MVC 2.0 Attributes.
  • ASP.NET MVC 2.0 Validation An overview of validation in ASP.NET MVC 2.0.
  • ASP.NET MVC 2.0 Areas A look at ASP.NET MVC 2.0 Areas.
  • ASP.NET MVC 2.0 and AJAX Part 1 ASP.NET MVC makes working with AJAX really easy; it's quite impressive how powerful the framework can be. JQuery adds extra features and makes AJAX calls really easy; we'll see that all here soon.
  • ASP.NET MVC 2.0 and AJAX Part 2 In this article, we are going to look at how you can utilize AJAX in your views, and utilize a concept called unobtrusive JavaScript to take advantage of a variety of situations. ASP.NET MVC provides AJAX features very easily as we previously saw, but this comes with a caveat, and it has mostly to do with the planning of the implementation. We’re going to examine these concerns in this article.
  • ASP.NET MVC 2.0 and ADO.NET Entity Framework - Part 1 In this article, we'll examine using the ADO.NET Entity Framework (ADO.NET EF). The 4.0 version has received some major upgrades, with some major API enhancements and fixes for most of the pain points within the designer.
  • ASP.NET MVC 2.0 and ADO.NET Entity Framework - Part 2 Out of the .NET framework 4.0 comes many great enhancements, the ADO.NET entity framework (ADO.NET EF) is among the top. The framework has improved upon some of the previous bugs (in version 1), as well as enhanced the API, including many new LINQ-to-SQL-like improvements. We're going to examine using these API features to create a generic version of of a data repository.
  • Complexity in ASP.NET MVC, Part 1: Dealing With Large Models At times, every developer has a web forms page or MVC view that ends up getting pretty complex, for various reasons. Whether it pulls in and integrates a lot of data (such as a portal page) or allows users to edit a lot of information, applications require data, and the amount of data grows over time. It’s a simple reality. We’re going to examine what a larger ASP.NET MVC view looks like, and some actions we can take to keep the model instantiation code as slim as possible.
  • Complexity in ASP.NET MVC, Part 2: Plan your AJAX Carefully Brian Mains discusses management of Ajax requests in ASP.NET MVC.
  • Using DI Containers in ASP.NET MVC How to use Dependency Injection containers in ASP.NET MVC.
  • Using Microsoft Unity in ASP.NET MVC Brian Mains continues his asp.net series with the unity application block.
  • Introduction

    The ASP.NET MVC framework was a giant leap into the Alt.Net world of development for Microsoft, through Alt.Net ideas and principles have been practiced for ages before this framework was released. The framework itself provides flavors of aspect-oriented programming, loose coupling by convention, and a variety of other great features.

    One common recurring feature that is mentioned in articles and blogs is the ability to use a Dependency Injection (DI) container to load dependencies between objects. This approach utilizes many great principles of object oriented programming, but this begs a question first: what is a DI container?

    Overview of Dependency Injection

    You may have written the following lines of code many times, where one object requires the existence of another object that is passed through the constructor, as shown in Listing 1.

    Listing 1: Creating an object

    This code is simple, but it creates a dependency, stating that ObjectB relies on ObjectA through a direct reference. We could, however, create a looser coupling by creating the interface IObjectA (that ObjectA implements) and use IObjectA as the constructor for ObjectB, as in:

    Listing 2: Loose Coupling Through an Interface

    IObjectA could technically be many types and is not restricted to one type of class, which creates a looser coupling between ObjectA and ObjectB. To go even further, suppose ObjectA belongs to a bigger scope of the project, and is a common object reused across the project. Rather than pass ObjectA to each of these multiple classes that use it, the DI container can take over the responsibility of creating objects. Since Objects B, C, D, etc. use ObjectA, the program can setup our one ObjectA reference, and everytime it finds an IObjectA interface defined in the constructor (in this case, Objects B, C, D, etc.), it inserts it automatically for us without us having to do any extra work. This saves us a lot of time inserting the reference, and changes our code slightly to look like the following:

    Listing 3: Using a DI container

    This approach gives away the responsibility for creating an object to ObjectB, which now becomes a responsibility given to the DI container. The DI container maps an object instance to its object or interface type it defines. In Listing 3, ObjectA mapped to the IObjectA type. Anytime the DI container finds a reference to IObjectA in ObjectB's constructor or one of its properties, the DI container injects that reference at that spot.

    Each DI container has a different flavor in how the mappings are defined, but overall, from a concept perspective, each container performs the similar task of mapping a type to an instance. For instance, one of the core approaches to setting up the mappings is through a configuration or XML file. Some containers also have the ability to register references through code too.

    Injection Types

    Dynamic injection typically happens in one of two ways. The first is constructor injection, where the DI container actually performs the construction of the object. For instance, if a class had a constructor as in Listing 4, the DI container examines each parameter and attempts to insert a reference.

    Listing 4: Sample Constructor

    The DI container examines the constructor for ObjectA. It inspects each of the parameter types against the types defined within the DI container, using similar pseudo logic as in the following:

    • IObjectB – IObjectB type is mapped to an instance of ObjectB and passed dynamically to the constructor
    • IObjectC – IObjectC type is mapped to an instance of ObjectC and passed dynamically to the constructor
    • IObjectD – No registration exists in the DI container; pass null
    • ObjectEClass – ObjectEClass matches an object of the same type, and is passed dynamically to the constructor

    As you can see, if a type doesn't exist in the DI container, it may pass null or some other default, depending on its behavior.

    The next type of injection is setter injection. This process examines each property of an object and dynamically invokes its setter when the condition is right. The DI container may map to the property type for the lookup, or sometimes a special attribute is used to designate that the property should be injected into.

    Why Dynamic Injection

    One of the bigger reasons to use dependency injection is that it loosely couples your design. Components deal with interfaces and concrete types, but don't necessarily know where the related objects come from, which minimizes the instantiation code we often have to write. Additionally, this creates a more testable design. At the time of implementation, the DI container will inject the actual implementation, but during testing, we can inject a fake implementation that does nothing but return the fixed data we want it to. We'll see examples of this in the next section.

    ASP.NET MVC

    ASP.NET MVC can utilize constructor injection by opening up constructor references in the controller, and storing them in local variables for the action methods to use, as shown in Listing 5.

    Listing 5: Sample Constructor Injection

    As I mentioned previously, but specific to ASP.NET MVC, constructor injection makes it easier for developers to test their controller code by performing the following kind of test at runtime:

    Listing 6: Faking the Results Using a Mocking Library (TypeMock)

    When it comes time to run the application, the ASP.NET MVC framework will use the real implementation of IHomeRepository to pull from the database. However, since the lifecycle manages the contruction of the controller, we need to customize the process that builds the controller, to use our injection container.

    The DefaultControllerFactory class is the object that constructs the controller. The easiest approach to customizing this process is to inherit the default behavior from DefaultControllerFactory, the default instance.

    Listing 7: Using a Custom Controller Factory

    We'll see more details of this in the next article.

    Conclusion

    Dependency Injection is another step toward loose coupling of references in an application. But not only that, it intends to require you to write less code to manage interdependencies between objects and managing the creation of your application singleton objects.

    The ASP.NET MVC 2 Series

  • Introduction to ASP.NET MVC 2.0 In this article, we'll begin examining the new features of ASP.NET MVC 2.0 by comparing what ASP.NET MVC offers against its predecessor, ASP.NET web forms.
  • ASP.NET MVC 2.0 User Interfaces The next part to this article series on MVC 2.0 is the user interface. We saw in the last article some basics on the changes of the user interface, which we'll delve into more in this article series. Here we will begin to look at how developers can construct the view user interface.
  • ASP.NET MVC 2.0 Using Multiple Actions Brian Mains explains how to use multiple actions in ASP.NET MVC 2.0.
  • ASP.NET MVC 2.0 Templating Templating is now in the ASP.NET MVC 2.0 framework, for .NET framework 3.5 and 4.0. We are going to take a look at these features.
  • ASP.NET MVC 2.0 Attributes An overview of ASP.NET MVC 2.0 Attributes.
  • ASP.NET MVC 2.0 Validation An overview of validation in ASP.NET MVC 2.0.
  • ASP.NET MVC 2.0 Areas A look at ASP.NET MVC 2.0 Areas.
  • ASP.NET MVC 2.0 and AJAX Part 1 ASP.NET MVC makes working with AJAX really easy; it's quite impressive how powerful the framework can be. JQuery adds extra features and makes AJAX calls really easy; we'll see that all here soon.
  • ASP.NET MVC 2.0 and AJAX Part 2 In this article, we are going to look at how you can utilize AJAX in your views, and utilize a concept called unobtrusive JavaScript to take advantage of a variety of situations. ASP.NET MVC provides AJAX features very easily as we previously saw, but this comes with a caveat, and it has mostly to do with the planning of the implementation. We’re going to examine these concerns in this article.
  • ASP.NET MVC 2.0 and ADO.NET Entity Framework - Part 1 In this article, we'll examine using the ADO.NET Entity Framework (ADO.NET EF). The 4.0 version has received some major upgrades, with some major API enhancements and fixes for most of the pain points within the designer.
  • ASP.NET MVC 2.0 and ADO.NET Entity Framework - Part 2 Out of the .NET framework 4.0 comes many great enhancements, the ADO.NET entity framework (ADO.NET EF) is among the top. The framework has improved upon some of the previous bugs (in version 1), as well as enhanced the API, including many new LINQ-to-SQL-like improvements. We're going to examine using these API features to create a generic version of of a data repository.
  • Complexity in ASP.NET MVC, Part 1: Dealing With Large Models At times, every developer has a web forms page or MVC view that ends up getting pretty complex, for various reasons. Whether it pulls in and integrates a lot of data (such as a portal page) or allows users to edit a lot of information, applications require data, and the amount of data grows over time. It’s a simple reality. We’re going to examine what a larger ASP.NET MVC view looks like, and some actions we can take to keep the model instantiation code as slim as possible.
  • Complexity in ASP.NET MVC, Part 2: Plan your AJAX Carefully Brian Mains discusses management of Ajax requests in ASP.NET MVC.
  • Using DI Containers in ASP.NET MVC How to use Dependency Injection containers in ASP.NET MVC.
  • Using Microsoft Unity in ASP.NET MVC Brian Mains continues his asp.net series with the unity application block.
  • <<  Previous Article Continue reading and see our next or previous articles Next Article >>

    About Brian Mains

    Brian Mains is an application developer consultant with Computer Aid Inc. He formerly worked with the Department of Public Welfare. In both places of business, he developed both windows and web applications, small and large, using the latest .NET technologies. In addition, he had spent many hou...

    This author has published 73 articles on DotNetSlackers. View other articles or the complete profile here.

    Other articles in this category


    Code First Approach using Entity Framework 4.1, Inversion of Control, Unity Framework, Repository and Unit of Work Patterns, and MVC3 Razor View
    A detailed introduction about the code first approach using Entity Framework 4.1, Inversion of Contr...
    Exception Handling and .Net (A practical approach)
    Error Handling has always been crucial for an application in a number of ways. It may affect the exe...
    jQuery Mobile ListView
    In this article, we're going to look at what JQuery Mobile uses to represent lists, and how capable ...
    Book Review: SignalR: Real-time Application Development
    A book review of SignalR by Simone.
    JQuery Mobile Widgets Overview
    An overview of widgets in jQuery Mobile.

    You might also be interested in the following related blog posts


    ASP.Net MVC What are the uses of Display, DisplayName, DisplayFormat and ScaffoldColumn attributes? read more
    Understanding the MvcRouteHandler and MvcHandler in ASP.NET MVC read more
    Display inline images in ASP.NET MVC view directly from ViewModel properties read more
    Use MvcContrib Grid to Display a Grid of Data in ASP.NET MVC read more
    Building Distributed Applications in ASP.NET MVC at MvcConf 2010 on 7/22/2010 read more
    MSDN Guidance on ASP.NET MVC vs WebForms and its Impact on my EF + ASP.NET Work read more
    ASP.NET 4.0 Dynamic Data and Many to Many Entity Framework Entities read more
    RadElement Lifecycle – a WinForms TPF Story read more
    November's Toolbox Column Now Online read more
    Podcast #1 – interview with Ben Scheirman co-author of ASP.NET MVC in Action read more
    Top
     
     
     

    Discussion


    Subject Author Date
    placeholder Real world examples GAston Breaux 9/25/2010 10:49 PM
    RE: Real world examples Brian Mains 9/25/2010 11:47 PM
    placeholder RE: Real world examples GAston Breaux 9/27/2010 9:26 PM

    Please login to rate or to leave a comment.