Dependency Injection in ASP.NET Web API 2

What is Dependency Injection?

A dependency is any object that another object requires. For example, it‘s common to define a repository that handles data access. Let‘s illustrate with an example. First, we‘ll define a domain model:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}
Here is a simple repository class that stores items in a database, using Entity Framework.

public class ProductsContext : DbContext
{
    public ProductsContext()
        : base("name=ProductsContext")
    {
    }
    public DbSet<Product> Products { get; set; }
}

public class ProductRepository : IDisposable
{
    private ProductsContext db = new ProductsContext();

    public IEnumerable<Product> GetAll()
    {
        return db.Products;
    }
    public Product GetByID(int id)
    {
        return db.Products.FirstOrDefault(p => p.Id == id);
    }
    public void Add(Product product)
    {
        db.Products.Add(product);
        db.SaveChanges();
    }

    protected void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (db != null)
            {
                db.Dispose();
                db = null;
            }
        }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}
Now let‘s define a Web API controller that supports GET requests for Product entities. (I‘m leaving out POST and other methods for simplicity.) Here is a first attempt:

public class ProductsController : ApiController
{
    // This line of code is a problem!
    ProductRepository _repository = new ProductRepository();

    public IEnumerable<Product> Get()
    {
        return _repository.GetAll();
    }

    public IHttpActionResult Get(int id)
    {
        var product = _repository.GetByID(id);
        if (product == null)
        {
            return NotFound();
        }
        return Ok(product);
    }
}
Notice that the controller class depends on ProductRepository, and we are letting the controller create the ProductRepository instance. However, it‘s a bad idea to hard code the dependency in this way, for several reasons.

If you want to replace ProductRepository with a different implementation, you also need to modify the controller class.
If the ProductRepository has dependencies, you must configure these inside the controller. For a large project with multiple controllers, your configuration code becomes scattered across your project.
It is hard to unit test, because the controller is hard-coded to query the database. For a unit test, you should use a mock or stub repository, which is not possible with the currect design.
We can address these problems by injecting the repository into the controller. First, refactor the ProductRepository class into an interface:

public interface IProductRepository
{
    IEnumerable<Product> GetAll();
    Product GetById(int id);
    void Add(Product product);
}

public class ProductRepository : IProductRepository
{
    // Implementation not shown.
}
Then provide the IProductRepository as a constructor parameter:

public class ProductsController : ApiController
{
    private IProductRepository _repository;

    public ProductsController(IProductRepository repository)
    {
        _repository = repository;
    }

    // Other controller methods not shown.
}
This example uses constructor injection. You can also use setter injection, where you set the dependency through a setter method or property.

But now there is a problem, because your application doesn‘t create the controller directly. Web API creates the controller when it routes the request, and Web API doesn‘t know anything about IProductRepository. This is where the Web API dependency resolver comes in.

The Web API Dependency Resolver

Web API defines the IDependencyResolver interface for resolving dependencies. Here is the definition of the interface:

public interface IDependencyResolver : IDependencyScope, IDisposable
{
    IDependencyScope BeginScope();
}

public interface IDependencyScope : IDisposable
{
    object GetService(Type serviceType);
    IEnumerable<object> GetServices(Type serviceType);
}
The IDependencyScope interface has two methods:

GetService creates one instance of a type.
GetServices creates a collection of objects of a specified type.
The IDependencyResolver method inherits IDependencyScope and adds the BeginScope method. I‘ll talk about scopes later in this tutorial.

When Web API creates a controller instance, it first calls IDependencyResolver.GetService, passing in the controller type. You can use this extensibility hook to create the controller, resolving any dependencies. If GetService returns null, Web API looks for a parameterless constructor on the controller class.

Dependency Resolution with the Unity Container

Although you could write a complete IDependencyResolver implementation from scratch, the interface is really designed to act as bridge between Web API and existing IoC containers.

An IoC container is a software component that is responsible for managing dependencies. You register types with the container, and then use the container to create objects. The container automatically figures out the dependency relations. Many IoC containers also allow you to control things like object lifetime and scope.

Note: “IoC” stands for “inversion of control”, which is a general pattern where a framework calls into application code. An IoC container constructs your objects for you, which “inverts” the usual flow of control.

For this tutorial, we‘ll use Unity from Microsoft Patterns & Practices. (Other popular libraries include Castle Windsor, Spring.Net, Autofac,Ninject, and StructureMap.) You can use NuGet Package Manager to install Unity. From the Tools menu in Visual Studio, select Library Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:

Install-Package Unity
Here is an implementation of IDependencyResolver that wraps a Unity container.

using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Web.Http.Dependencies;

public class UnityResolver : IDependencyResolver
{
    protected IUnityContainer container;

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

    public object GetService(Type serviceType)
    {
        try
        {
            return container.Resolve(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return container.ResolveAll(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return new List<object>();
        }
    }

    public IDependencyScope BeginScope()
    {
        var child = container.CreateChildContainer();
        return new UnityResolver(child);
    }

    public void Dispose()
    {
        container.Dispose();
    }
}
If the GetService method cannot resolve a type, it should return null. If the GetServices method cannot resolve a type, it should return an empty collection object. Don‘t throw exceptions for unknown types.

Configuring the Dependency Resolver

Set the dependency resolver on the DependencyResolver property of the global HttpConfiguration object.

The following code registers the IProductRepository interface with Unity and then creates a UnityResolver.

public static void Register(HttpConfiguration config)
{
    var container = new UnityContainer();
    container.RegisterType<IProductRepository, ProductRepository>(new HierarchicalLifetimeManager());
    config.DependencyResolver = new UnityResolver(container);

    // Other Web API configuration not shown.
}
Dependenecy Scope and Controller Lifetime

Controllers are created per request. To manage object lifetimes, IDependencyResolver uses the concept of a scope.

The dependency resolver attached to the HttpConfiguration object has global scope. When Web API creates a controller, it calls BeginScope. This method returns an IDependencyScope that represents a child scope.

Web API then calls GetService on the child scope to create the controller. When request is complete, Web API calls Dispose on the child scope. Use the Dispose method to dispose of the controller’s dependencies.

How you implement BeginScope depends on the IoC container. For Unity, scope corresponds to a child container:

public IDependencyScope BeginScope()
{
    var child = container.CreateChildContainer();
    return new UnityResolver(child);
}
Most IoC containers have similar equivalents.

This article was originally created on January 20, 2014

link: http://www.asp.net/web-api/overview/advanced/dependency-injection

时间: 2024-10-27 13:21:51

Dependency Injection in ASP.NET Web API 2的相关文章

Dependency Injection in ASP.NET Web API 2 (在web api2 中使用依赖注入)

原文:http://www.asp.net/web-api/overview/advanced/dependency-injection 1 什么是依赖注入(Dependency Injection) 依赖,简单来说就是一个对象需要的任何其他对象.具体解释请Google或百度.在我们使用Web api2  开发应用程序时,通常都会遇到Controller  访问库 Repository 问题. 例如:我们定义一个Domain 对象 public class Product { public in

ASP.NET Web API是什么?

[翻译]ASP.NET Web API是什么? 说明:随微 软ASP.NET MVC 4一起发布的还有一个框架,叫做ASP.NET Web API.目前国内关注这项技术的人似乎还很少,这方面的文章也不多见.开发Web应用程序也许可以只用MVC这样的技术,而不用这项Web API技术,但如果用了,会给你的应用程序带来极大的好处.为此,本人转载并翻译了以下这篇文章,后面还会陆续翻译该项技术的一些官方教程.大家一起学 习,共同提高. Microsoft ASP.NET: What's This New

Asp.Net Web API 2 官网菜鸟学习系列导航[持续更新中]

前言 本来一直参见于微软官网进行学习的, 官网网址http://www.asp.net/web-api.出于自己想锻炼一下学习阅读英文文章的目的,又可以学习下微软新发布的技术,其实也很久了,但自己菜鸟一枚,对自己来说都是新技术了.鉴于以上两个原因,本人打算借助google翻译和有道词典,来翻译学习这个系列,并通过博客园来记录自己的翻译学习过程.由于自己阅读水平的确太菜,在借助工具的情况下,有时候搞出来的也是蹩脚的语句,自己读着都难受,尤其是到了Web API路由的那两篇,所以自己想着是不是有别人

Asp.Net Web API 2第十一课——在Web API中使用Dependency Resolver

前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 本文主要来介绍在Asp.Net Web API使用Web API的Decpendency Resolver在控制器中如何注入依赖. 本文使用VS2013.本文的示例代码下载链接为http://pan.baidu.com/s/1BvFTs 为什么要使用Dependency Resolver 一个dependency 其实就是一

ASP.NET Web API - 使用 Castle Windsor 依赖注入

示例代码 项目启动时,创建依赖注入容器 定义一静态容器 IWindsorContainer 1 private static IWindsorContainer _container; 在 Application_Start() 中,创建该容器 1 _container = new WindsorContainer(); 调用 Container Install 方法,向容器内注册组件 1 _container.Install(FromAssembly.This()); 该语句会调用整个程序集中

ASP.NET Web API 特性

1.先进的 HTTP 编程模型: 使用新的强类型的 HTTP 对象模型直接操作 HTTP 请求和响应, 在 HTTP客户端使用相同的编程模型和 HTTP 管道: 2.支持路由: Web API 完整支持 ASP.NET 路由, 包括路由参数和约束. 此外, 到动作的映射支持约定, 从此将不再需要向类或者方法添加类似于 [HttpPost] 之类的属性: 3.内容协商: 客户端与服务端可以一起决定 API 返回数据的格式. 默认支持 XML, JSON 以及 Form URL-Encoded 格式

ASP.NET Web API的Controller是如何被创建的?

Web API调用请求的目标是定义在某个HttpController类型中的某个Action方法,所以消息处理管道最终需要激活目标HttpController对象.调用请求的URI会携带目标HttpController的名称,该名称经过路由解析之后会作为路由变量保存到一个HttpRouteData对象中,而后者会被添加到代表当前请求的HttpRequestMessage对象的属性字典中.ASP.NET Web API据此解析出目标HttpController的类型,进而实现针对目标HttpCon

ASP.NET Web API 简介

ASP.NET Web API 简介 ASP.NET MVC 4 包含了 ASP.NET Web API, 这是一个创建可以连接包括浏览器.移动设备等多种客户端的 Http 服务的新框架, ASP.NET Web API 也是构建 RESTful 服务的理想平台. ASP.NET Web API 特性 ASP.NET Web API 包含下列特性: 先进的 HTTP 编程模型: 使用新的强类型的 HTTP 对象模型直接操作 HTTP 请求和响应, 在 HTTP客户端使用相同的编程模型和 HTTP

ASP.NET Web API系列教程(目录)(转)

注:微软随ASP.NET MVC 4一起还发布了一个框架,叫做ASP.NET Web API.这是一个用来在.NET平台上建立HTTP服务的Web API框架,是微软的又一项令人振奋的技术.目前,国内对此关注的人似乎还不多,有关ASP.NET Web API的文章也不多见.为此,本人打算对微软ASP.NET Web API官方网站上的一些教程进行翻译,以期让更多的国人了解.学习和使用这项ASP.NET Web API. ASP.NET Web API系列教程目录 Introduction:Wha