ASP. 2 The 11th lesson--Using dependency Resolver in the Web API

Source: Internet
Author: User

Objective

Before reading this article, you can also go to the ASP. NET Web API 2 series navigation to view http://www.cnblogs.com/aehyok/p/3446289.html

This article focuses on how the Decpendency resolver in the ASP. NET Web API uses the Web API to inject dependencies into the controller.

This article uses VS2013. The sample code download link for this article is Http://pan.baidu.com/s/1BvFTs

Why use dependency Resolver

A dependency is actually an interface that an object or another object needs. For example, in the ASP. 2 Lesson--crud operation Http://www.cnblogs.com/aehyok/p/3434578.html, we defined a productscontroller Class, this class requires an instance of Iproductrepository , and this implementation looks like this:

public class productscontroller:apicontroller{    private static iproductrepository repository = new Productrepository ();    

This is not the best design, because the invocation ProductRepository is created by hard coding in the controller. If you want to use the IProductRepository的不同实例,我们将需要在ProductRepository中改变代码。如果ProductsController不依赖于任何具体实例的IProductRepository那会是比较好的。

Dependency injection solved the problem. In dependency injection, objects are not responsible for creating their own dependencies. Instead, when you create an object, the dependency is injected by constructor arguments or setter methods.

Here is the modified implementation code in ProductsController:

public class productscontroller:apicontroller{    private readonly iproductrepository repository;    Public ProductsController (iproductrepository repository)    {        if (repository = = null)        {            throw new ArgumentNullException ("repository");        }        This.repository = repository;    }

This is better. You can now switch to another IProductRepository instance without touching the ProductsController implementation.

However, in the ASP. NET Web API, you cannot create a controller directly. Instead, the framework gives you the information to create a controller that it IProductRepository does not know about. This framework can only be used to create your controller by invoking a parameterless constructor.

At this time dependency resolver came. Dependency Resolver's job is to create the object that the framework needs, including Congtrollers objects. By providing a custom dependency resolver, you can create a controller instance on behalf of the framework.

A simple dependency resolver.

The following code shows a simple dependency resolver. This code basically just shows how dependency injection works in the Web API. After that, we will see how to merge the container of an IOC.

Class simplecontainer:idependencyresolver{    static readonly iproductrepository respository = new Productrepository ();    Public Idependencyscope BeginScope ()    {        //This example does not the support child scopes, so we simply return ' this '. C5/>return this;     }    public Object GetService (Type servicetype)    {        if (servicetype = = typeof (ProductsController))        {            return new ProductsController (respository);        }        else        {            return null;        }    }    Public ienumerable<object> getservices (Type servicetype)    {        return new list<object> ();    public void Dispose ()    {        //If BeginScope returns ' This ', the Dispose method must is a no-op.    }}

A dependency resolver implements this Idependencyresolver interface. This idependencyresolver interface inherits the additional two interfaces Idependencyscope ,IDisposable.

Namespace system.web.http.dependencies{public    interface Idependencyresolver:idependencyscope, IDisposable    {        idependencyscope beginscope ();    }    Public interface idependencyscope:idisposable    {        object GetService (Type servicetype);        Ienumerable<object> getservices (Type servicetype);}    }

The Idependencyscope interface defines two methods:

    • GetService: Creating an instance of a specified type
    • getservices: Creates a collection object of the specified type

For the controller, the framework calls GetService to get a single instance of the controller. This is our simple container to create a controller and inject repository.

For any type that your dependency resolver does not handle,GetService will return null,getservices will also return an empty collection object, and in particular, do not throw an exception of an unknown type.

This idependencyresolver interface inherits the Idependencyscope and Adds a method:

    • beginscope: Creating a nested scope

Later, we'll discuss how nested scopes manage the life cycle of our objects in the future. Now, the implementation of theBeginScope method We simply return a this.

Setting the Dependency Resolver

The dependency Resolver is now set in the Web API global configuration object.

Mainly in the Global.asax of this file. Then in the Application_Start method, set GlobalConfiguration.Configuration.DependencyResolver to your dependency Reslover.

public class webapiapplication:system.web.httpapplication{    void Configureapi (httpconfiguration config)    {        CONFIG. Dependencyresolver = new Simplecontainer ();    }    protected void Application_Start ()    {        configureapi (globalconfiguration.configuration);        // ...    }}

So now you can run the program properly.

Scope and Object declaration cycles

The controller is created for each request. To help manage the declaration cycle of objects,Idependencyresolver uses the IDisposable interface. The dependency resolver object that is added to the httpconfiguration has a global scope. When the framework creates a new controller instance, it calls Idependencyresolver.beginscope. This method returns a idependencyscope . The framework Idependencyscope up the GetService to get the controller. When the framework finishes processing the request, it calls Dispose in the child scope. You can use the Dispose method to release the controller's dependencies.

Dependency Injection with IoC Containers

An IOC container is a software component that is responsible for creating dependencies. The IOC container provides a common framework for dependency injection. If you use an IOC container, you do not need to go directly along with the object in the code, several open source. Net IOC containers are available, such as AUTOFAC, Castle Windsor, Ninject, spring.net, StructureMap, etc.

In the following example we use Unity, the IOC container developed by Microsoft patterns & practices.

namespace productstore{using System;    Using System.Collections.Generic;    Using System.Web.Http;    Using System.Web.Http.Dependencies;    Using Microsoft.Practices.Unity;        Class Scopecontainer:idependencyscope {protected Iunitycontainer container; Public Scopecontainer (Iunitycontainer container) {if (container = = null) {th            Row new ArgumentNullException ("container");        } This.container = container; public Object GetService (Type servicetype) {if (container. Isregistered (servicetype)) {return container.            Resolve (servicetype);            } else {return null; }} public ienumerable<object> getservices (Type servicetype) {if (container. Isregistered (servicetype)) {return container.            ResolveAll (servicetype);            }else {return new list<object> (); }} public void Dispose () {container.        Dispose (); }} class Ioccontainer:scopecontainer, Idependencyresolver {public Ioccontainer (Iunitycontainer contain ER): Base (Container) {} public Idependencyscope BeginScope () {var Chi ld = container.            Createchildcontainer ();        return new Scopecontainer (child); }    }}

This ScopeContainer class implements the Idependencyscope representation of a sub-range. This IoCContainer class implements dependency resolution in the global scope. and create a new Scopecontainer object in the beginscope method. This Unity container also has a sub-container concept. Because we can initialize ScopeContainer it with the child container of unity . thisScopeContainer.Dispose方法释放了Unity的子容器。

The following code registers the controller and repository with unity, and then sets the dependency resolver.

void Configureapi (httpconfiguration config) {    var unity = new UnityContainer ();    Unity. Registertype<productscontroller> ();    Unity. Registertype<iproductrepository, productrepository> (        new Hierarchicallifetimemanager ());    Config. Dependencyresolver = new Ioccontainer (unity);}

Each time the HTTP request is made, the Web API controller is created and then the controller is freed after the request is processed.

Now the same can be run.

Summarize

The study of dependency injection is not as deep as it is, and it only knows how to use it easily.

For the text

    Public Idependencyscope BeginScope ()    {        //This example does not the support child scopes, so we simply return ' this '. C4/>return this;     }

If this is not the case, then what else can be used, and further in-depth is needed. After that, you have to study the dependency injection that relies on unity. But it feels like there's no MEF.

The reference link for this article is Http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver

This article synchronizes to the Web API series navigation in http://www.cnblogs.com/aehyok/p/3446289.html

The sample code download link for this article is Http://pan.baidu.com/s/1BvFTs

ASP. 2 The 11th lesson--Using dependency Resolver in the Web API

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.