Published: 25 Oct 2010
By: Brian Mains

Using Microsoft Unity 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

    Microsoft created the Unity Application Block, currently in its 2.0 version, to provide dependency injection services to your application.

    The application block maps a contract type to an instance. Every time it finds a contract type defined, it injects the instance that was mapped. For instance, is given the following class:

    The Unity application block can map the ICustomerRepository contract to the CustomersRepository instance. In addition, the type of the instance can also be used as the contract, mapping CustomersRepository type to the instance itself, as we shall soon see.

    Starting with Unity

    What the Unity application block attempts to do is define a type defined as the contract and a type defined as the implementation (the mapped type). What I mean is that the contract type says "anytime I find a given type, inject a type in its place." This works perfectly when the contract type is an interface (ICustomerRepository) and the mapped type is a class (CustomerRepository). However, the contract and mapped type can be the same.

    The following methods in Listing 1 give you the ability to create these mappings through code, but of course that isn't the only way.

    Listing 1: Available Methods

    In the cases where the RegisterType method is used, the type specified will be dynamically constructed; otherwise, RegisterInstance accepts a pre-built instance to insert into the container.

    Note that some of the overrides can accept a name; this allows multiple registrations per type.

    Additionally, we can use the configuration file to register types for construction. Obviously, instances can't be registered directly through the configuration file, but the contract and mapped types can both be registered, as well as the ability to control other aspects of the creation as well (such as which constructor to call in case there are multiple constructor overloads).

    Listing 2: Defining a Configuration Section

    This example defines two repositories used within the application. Each of these mappings is passed to the container using the RegisterType method. Additionally, a lifetime container can be specified with a child <lifetime /> attribute (more on this later), as well as the appropriate constructor to call when creating the mapped type. This is important because Unity, by default, tries to call the constructor with the most arguments, attempting to inject from its container any references it can find. This can be a problem at times, but luckily we can control this behavior by calling the empty override with an empty <constructor /> definition. Additionally, <param /> arguments can be specified to choose the correct overload to call. The unity container is very flexible, and more than I can cover in a single article.

    The configuration file doesn't automatically load references into the container; instead, we have to write some code to perform this last step:

    Listing 3: Loading the Configurations

    Type Construction

    In this way, you may think Unity is simply a type constructor, only injecting Mapped object B when it finds contract A. But it's so much more than that, as we'll see. Let's begin by looking at the example in Listing 3.

    Listing 4: Resolving References

    In Listing 3, the Resolve method actually constructs a CustomerRepository instance; note that CustomerRepository does not exist within the container. This is because at this point, the Unity container is going to examine the CustomerRepository class and inject objects into the constructor of CustomerRepository defined in Listing 4:

    Listing 5: Constructor Injection

    It also looks for properties that can be written to with the [Dependecy] attribute defined. Anywhere it finds these types of injections, it will attempt to inject into it a value from the container. If you happened to register a type through the RegisterType method, the type registered will be constructed, and any of its references resolved. If you used RegisterInstance, the instance passed in is injected.

    Additionally, maybe you already have an instance created that you want to inject references through its properties. This is possible too, using the BuildUp method, which works the same ways as the Resolve method.

    Lifetime Managers

    An object added to a container has a given lifetime associated to it. If you examine the source, the default lifetime uses the container-controlled lifetime manager, but there can be other options too, such as using a per-thread approach, or a one-time lifetime container, or even a custom one. I'm going to illustrate a custom lifetime container, as it makes it easier to understand the inner workings. A common example you see on the web is shown below.

    Listing 6: Using the Http Context for a Lifetime Manager

    Since the current HTTP request, through the HttpContext, has an items collection open for a single ASP.NET request, this makes it a good option for storing individual references. Notice it's a generic, meaning that we pass a type when constructing the argument. This type signifies the object being stored in the container, and is used to read and write to/from the container. This is important because the lifetime container manages a single object, and thus, we need to ensure the storage of that object is distinct. The items dictionary ensures that distinctness, and can be utilized in ASP.NET MVC.

    The Unity container is a pretty complex object with a lot of options for dynamic injection, and unfortunately, I've run out of time to illustrate all of its capabilities. The following links may help you read more about the container instance.

    ASP.NET MVC Extensions

    So how can we leverage Microsoft Unity in our applications? The common practice for Dynamic Injection in ASP.NET MVC is through the constructor of a controller. A lot of examples are out there that implement this, and here is a good example of one implementation, that also supports unit testing.

    I wanted to go beyond what was already out there, but to be inclusive of other areas where this may be applicable. The next possible point for injection exists within an action invoker. By creating a class that inherits from ControllerActionInvoker, we can inject in parameter values into the action method when its invoked. The key is the GetParameterValue method; this method takes a reference to the ParameterDescriptor class, which has all of the information about the existing parameter of the action method being executed. It would be very easy to inject additional references into each action method that runs.

    Listing 7: Injecting References into the Action

    Additionally, you may have seen the Service Location application block offered by the Enterprise Library. The Unity container could also serve a similar purpose, serving up references whenever we need one. We could expose an IServiceLocator interface, store it as a singleton, and define a GetService method to do something like the following.

    Listing 8: Using Service Location with Unity

    Now that we have a unity container reference stored globally, we could push any reference to the entire application at the various levels, whether in the UI, in the business layer, in the data layer, or anywhere else the IServiceLocator interface is recognized.

    Conclusion

    We've looked at the core interfaces for unity, as well as some references to additional information, and how it can apply to ASP.NET MVC at various steps in the lifecycle.

    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...
    jQuery Mobile ListView
    In this article, we're going to look at what JQuery Mobile uses to represent lists, and how capable ...
    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 Widgets Overview
    An overview of widgets in jQuery Mobile.
    Book Review: SignalR: Real-time Application Development
    A book review of SignalR by Simone.

    You might also be interested in the following related blog posts


    Understanding the MvcRouteHandler and MvcHandler in ASP.NET MVC read more
    Building an Senchas ExtJS 4.0 MVC Application With Microsofts ASP.NET MVC3 Series / Basics read more
    MSDN Guidance on ASP.NET MVC vs WebForms and its Impact on my EF + ASP.NET Work read more
    November's Toolbox Column Now Online read more
    Html Encoding Nuggets With ASP.NET MVC 2 read more
    Get Ready for Teleriks Custom-built Extensions for ASP.NET MVC read more
    Adding IIS Manager Users and Permissions using PowerShell read more
    Important releases from Microsoft you may have missed read more
    Announcing Let Me Bing That For You read more
    MvcContrib working on Portable Areas read more
    Top
     
     
     

    Discussion


    Subject Author Date
    placeholder RE: HttpContextLifetimeManager Vitaly K 3/23/2011 12:33 PM
    RE: RE: HttpContextLifetimeManager Brian Mains 3/23/2011 7:31 PM

    Please login to rate or to leave a comment.