DOCX

introduction to ASP.NET MVC Dependency Injection in VS2010

By Francisco Tucker,2014-09-19 17:39
10 views 0
introduction to ASP.NET MVC Dependency Injection in VS2010

Hands-On Lab

    ASP.NET MVC Dependency Injection

Lab version: 1.1.0

    Last updated: 9/19/2011

    Page 1

CONTENTS

    OVERVIEW ............................................................................................................................................. 3

    EXERCISE 1: INJECTING A CONTROLLER .......................................................................................... 5

    Task 1 Running the Application ..................................................................................................... 8

    Task 2 Including Unity into MvcMusicStore Solution ..................................................................... 9

    Task 3 Adding a Unity Controller Factory ..................................................................................... 10

    Task 4 Registering Unity in Global.asax.cs Application_Start ........................................................ 11

    Task 5 Running the Application ................................................................................................... 13

    EXERCISE 2: INJECTING A VIEW ....................................................................................................... 14

    Task 1 Creating a View that Consumes a Service ......................................................................... 15

    Task 2 Including a Custom Dependency Resolver and a Custom View Page Activator .................. 16

    Task 3 Registering for Dependency Injection in Global.asax.cs Application_Start ......................... 19

    Task 4 Running the Application ................................................................................................... 21

    EXERCISE 3: INJECTING ACTION FILTERS ....................................................................................... 22

    Task 1 Including the Tracking Filter in the Solution ...................................................................... 22

    Task 2 Registering and Enabling the Filter ................................................................................... 26

    Task 3 Running the Application ................................................................................................... 27

    SUMMARY ............................................................................................................................................ 30

    Page 2

Overview

    Note: This Hands-on Lab assumes you have basic knowledge of ASP.NET MVC and ASP.NET MVC 3

    filters. If you have not used ASP.NET MVC 3 filters before, we recommend you to go over ASP.NET

    MVC Custom Action Filters and MVC Global and Dynamic Action filters Hand-on Lab.

    In Object Oriented Programming paradigm, objects work together in a collaboration model where there are contributors and consumers. Naturally, this communication model generates dependencies between objects and components that could became difficult to manage when complexity increases .

Figure 1

    Class dependencies and model complexity

    You have probably heard about the Factory Pattern and the separation between the interface and the implementation using services. However, the client objects are often responsible for service location. Before introducing the Dependency Injection Pattern, we will explain what Inversion of Control (IoC) principle is.

    With Inversion of Control (Ioc), consumer objects do not create the other objects on which they rely. Those objects come from an external source.

    The Dependency Injection (DI) Design Pattern

    Dependency injection (DI) design pattern is based on separating component behavior from dependency resolution without object intervention.

    This pattern is a particular implementation of Inversion of Control, where the consumer object receives his dependencies inside constructor properties or arguments.

    DI requires a framework component behind to deal with class constructor.

    Page 3

Figure 2

    Overview Dependency Injection diagram

    The advantages of using Dependency Injection pattern and Inversion of Control are the following:

    ; Reduces class coupling

    ; Increases code reusing

    ; Improves code maintainability

    ; Improves application testing

    Note: Depencency Injection is sometimes compared with Abstract Factory Design Pattern, but there is a slight difference between both approaches. DI has a Framework working behind to solve dependencies by calling the factories and the registered services.

    Now that you understand the Dependency Injection Pattern, you will learn through this lab how to apply it on ASP.NET MVC 3. You will start using Dependency Injection on Controllers to include a service for

    database access. Next you will use Dependency Injection on Views to use a service inside a view and

    display information. Then, you will extend DI to MVC 3 Filters concept and inject a Custom Action Filter

    in the solution.

    In this Hands-on Lab, you will learn how to:

    ; Integrate MVC 3 with Unity Application Block for Dependency Injection

    ; Use dependency injection inside an MVC Controller

    ; Use dependency injection inside an MVC View

    ; Use dependency injection inside an MVC Action Filter

    Page 4

    Note: This Lab proposes Unity Application Block as the dependency resolver framework, but it is posible to adapt any Dependency Injection Framework to work with MVC 3.

System Requirements

    You must have the following items to complete this lab:

    ; ASP.NET and ASP.NET MVC 3

    ; Visual Studio 2010

    ; SQL Server Database (Express edition or above)

    Note: You can install the previous system requirements by using the Web Platform Installer

    3.0: http://go.microsoft.com/fwlink/?LinkID=194638.

Exercises

    This Hands-On Lab is comprised by the following exercises:

    1. Exercise 1: Injecting a Controller

    2. Exercise 2: Injecting a View

    3. Exercise 3: Injecting Filters

Estimated time to complete this lab: 30 minutes.

    Note: Each exercise is accompanied by an End folder containing the resulting solution you should obtain after completing the exercises. You can use this solution as a guide if you need additional help

    working through the exercises.

Next Step

    Exercise 1: Injecting a Controller

    Exercise 1: Injecting a Controller

    Page 5

In this exercise, you will learn how to use Dependency Injection in MVC Controllers, by integrating Unity

    Application Block. For that reason you will include services into your MVC Music Store controllers to separate the logic from the data access. The service will create a new dependence into the controller constructor that will be resolved using Dependency Injection with the help of Unity application block.

    With this approach you will learn how to generate less coupled applications, which are more flexible and

    easier to maintain and test. Additionally, you will also learn how to integrate MVC with Unity. About StoreManager Service

    The MVC Music Store provided in the begin solution now includes a service that manages the Store Controller data, StoreService. Below you will find the Store Service implementation. Note that all the methods return Model entities.

    C# - StoreService.cs

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Web;

    using MvcMusicStore.Models;

namespace MvcMusicStore.Services

    {

     public class StoreService : MvcMusicStore.Services.IStoreService

     {

     MusicStoreEntities storeDB = new MusicStoreEntities();

     public IList<string> GetGenreNames()

     {

     var genres = from genre in storeDB.Genres

     select genre.Name;

     return genres.ToList();

     }

     public Genre GetGenreByName(string name)

     {

     var genre = storeDB.Genres.Include("Albums")

     .Single(g => g.Name == name);

     return genre;

     }

     public Album GetAlbum(int id)

     {

     var album = storeDB.Albums.Single(a => a.AlbumId == id);

     return album;

     }

    Page 6

     }

    }

    Additionally, in the StoreController you will find in the begin solution now uses StoreService. All data references were removed from Store Controller, and therefore it is possible to modify the current data

    access provider without making changes at any method that consumes the Store Service.

    You will find below that the Store Controller implementation has a dependency with the Store Service

    inside the class constructor.

    Note: The dependency introduced in this exercise is related to MVC Inversion of Control (IoC).

    The StoreController class constructor receives an IStoreService parameter, which is essential to perform service calls inside the class. However, StoreController does not implement the default constructor (with no parameters) that any controller must have to work with IoC.

    To resolve the dependency, the controller should be created by an abstract factory (a class that returns

    any object of the specified type).

C# - StoreController.cs

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Web;

    using System.Web.Mvc;

    using MvcMusicStore.ViewModels;

    using MvcMusicStore.Models;

    using MvcMusicStore.Services;

namespace MvcMusicStore.Controllers

    {

     public class StoreController : Controller

     {

     private IStoreService service;

     public StoreController(IStoreService service)

     {

     this.service = service;

     }

     //

     // GET: /Store/

     public ActionResult Index()

     {

     // Create list of genres

     var genres = this.service.GetGenreNames();

    Page 7

     // Create your view model

     var viewModel = new StoreIndexViewModel

     {

     Genres = genres.ToList(),

     NumberOfGenres = genres.Count()

     };

     return View(viewModel);

     }

     //

     // GET: /Store/Browse?genre=Disco

     public ActionResult Browse(string genre)

     {

     var genreModel = this.service.GetGenreByName(genre);

     var viewModel = new StoreBrowseViewModel()

     {

     Genre = genreModel,

     Albums = genreModel.Albums.ToList()

     };

     return View(viewModel);

     }

     //

     // GET: /Store/Details/5

     public ActionResult Details(int id)

     {

     var album = this.service.GetAlbum(id);

     return View(album);

     }

     }

    }

Note: You will get an error when a class tries to create this Store Controller without sending the

    service interface, because there is not a parameterless constructor declared.

    Through this lab you will learn how to deal with this problem using Dependency Injection with Unity.

Task 1 Running the Application

    In this task, you will run the Begin application, which is now including the service into the Store

    Controller that separates the data access from the application logic.

    Page 8

    After browsing to the store you will receive an exception since the controller service is not passed as a parameter by default:

    1. Open the begin solution MvcMusicStore.sln at Source\Ex01-Injecting Controller\Begin.

    2. Press F5 to run the application.

    3. Browse to /Store to load Store Controller. You will get the error message “No parameterless

    constructor defined for this object”:

    Figure 3

    Error while running MVC Begin Application

    4. Close the browser.

    In the following steps you will work on the Music Store Solution to inject the dependency this controller needs.

Task 2 Including Unity into MvcMusicStore Solution

    In this task, you will include Unity Application Block 2.0 into your solution.

    Note: The Unity Application Block (Unity) is a lightweight, extensible dependency injection container with optional support for instance and type interception. It’s a general-purpose container for use in

    Page 9

any type of .NET application. It provides all the common features found in dependency injection

    mechanisms including: object creation, abstraction of requirements by specifying dependencies at

    runtime and flexibility, be deferring the component configuration to the container.

    You could read more about Unity 2.0 at msdn.

1. Open the begin solution MvcMusicStore.sln at Source\Ex01-Injecting Controller\Begin.

    2. In the MvcMusicStore project, add a reference to Microsoft.Practices.Unity.dll, which is

    included in Source\Assets\Unity 2.0\ folder of this lab.

Task 3 Adding a Unity Controller Factory

    In this task, you will add to the solution a custom controller factory for Unity. This class implements IControllerFactory interface, extending CreateController and ReleaseController methods to work with Unity. This factory will create the instances of the controllers that work with Dependency Injection.

    Note: A controller factory is an implementation of the IControllerFactory interface, which is responsible both for locating a controller type and for instantiating an instance of that controller type.

    The following implementation of CreateController finds the controller by name inside the Unity container and returns an instance if it was found. Otherwise, it delegates the creation of the controller

    to an inner factory. One of the advantages of this logic is that controllers can be registered by name.

    You can find IControllerFactory interface reference at msdn.

1. In the MvcMusicStore project, create a new folder named Factories, and add the

    UnityControllerFactory class, which is included in the Source\Assets folder of this lab.

    C# - UnityControllerFactory.cs

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Web;

    using System.Web.Mvc;

    using Microsoft.Practices.Unity;

    using System.Web.Routing;

    namespace MvcMusicStore.Factories

    {

     public class UnityControllerFactory : IControllerFactory

     {

     private IUnityContainer _container;

     private IControllerFactory _innerFactory;

     public UnityControllerFactory(IUnityContainer container)

    Page 10

Report this document

For any questions or suggestions please email
cust-service@docsford.com