[ASP.]05-Use Ninject

Source: Internet
Author: User

[ASP.
MVC Calf Road]05-using Ninject

The end of an article (Dependency injection (DI) and Ninject) in the [ASP. NET MVC Path] series is referred to in the ASP.
Two things to do with ninject in MVC, after this article, this article will use a practical example to demonstrate the application of Ninject in ASP.

In order to better understand and hold the content of this article, it is strongly recommended that beginners read the article before reading the dependency injection (DI) and Ninject.

This article directory:


Preparatory work

Create a new blank solution named Bookshop. In this solution, add an MVC empty application named Bookshop.webui, and a class library project named Bookshop.domain. The directory structure is as follows:

After the two projects have been added, add a reference to the Bookshop.domain project under the Bookshop.webui project.

Use NuGet to install Ninject packages for Bookshop.webui Engineering and Bookshop.domain Engineering (for a description of NuGet, read Dependency injection (DI) and Ninject). Can be installed through a visual window, or you can open the package
The Manager console (view-and other Windows->package Manager Console) performs the following command installation:

Install-package Ninject-project Bookshop.webui

Install-package Ninject-project Bookshop.domain

Description Installation succeeded:

Create a controller Factory

We know that in ASP. NET MVC, a client request is handled in the action of a particular controller. By default, ASP. NET MVC uses the built-in controller factory class Defaultcontrollerfactory to create a corresponding controller instance for a request. Sometimes the default controller factory does not meet our actual needs, and we need to extend this default behavior by creating a custom controller factory class that inherits from the Defaultcontrollerfactory class and overriding some of these methods. To do this, we create a folder named Infrastructure under the Bookshop.webui project, and add a factory class named Ninjectcontrollerfactory in the folder with the following code:

public class Ninjectcontrollerfactory:defaultcontrollerfactory {    private ikernel ninjectkernel;    Public Ninjectcontrollerfactory () {        Ninjectkernel = new Standardkernel ();        Addbindings ();    }    protected override IController GetControllerInstance (RequestContext requestcontext, Type controllertype) {        return Controllertype = = null? Null: (IController) Ninjectkernel.get (Controllertype);    }    private void Addbindings () {        //TODO: Add binding later    }}

Ninjectkernel.get (Controllertype) in the code above can be obtained to a controller instance. If you instantiate the Controller class manually is a very complex process, we do not know whether the controller class has a constructor with parameters, or what type of argument the constructor is. Using Ninject only requires the use of one of the get methods above, and Ninject internally handles all dependencies automatically, intelligently creating the objects we need.

Once the Controller factory class is created, we need to tell MVC to use our Ninjectcontrollerfactory class to create the Controller object, which is required in the Global.asax file Application_ Add the following code to the Start method:

protected void Application_Start () {    ...    Set up controller factory    ControllerBuilder.Current.SetControllerFactory (New Ninjectcontrollerfactory ());}

Here we do not care about the above code is what the principle, know that set up a custom controller factory must be registered in this line, I will be in the next blog post on this part of the more in-depth explanation.


Add Domain Model

In an MVC application, everything revolves around the domain model. So we built a folder called entities in the Bookshop.domain project to store the domain entity model. As an e-commerce online bookstore, of course, one of the most important domain entities is book. Because just for demonstration, we simply define a book class and add the class to the Entities folder with the following code:

public class Book {public    int ID {get; set;}    public string Title {get; set;}    public string ISBN {get; set;}    public string Summary {get; set;}    public string Author {get; set;}    Public byte[] Thumbnail {get; set;}    Public decimal price {get; set;}    Public DateTime Published {get; set;}}

Add Repository

We know that we definitely need a way to read the book data from the database. In this case, we do not have to provide a ibookrepository interface for the data user (the controller here), which declares a iqueryable<book> type of attribute books in this interface. Thus, using dependency injection through this interface, the user can get the books data collection without worrying about how the data is obtained. To do this, we add a folder named Abstract in the Bookshop.domain project, where we add our Ibookrepository interface file with the following code:

Public interface Ibookrepository {    iqueryable<book> Books {get;}}

In MVC we typically use the Warehousing model (Repository pattern) to separate the data-related logic from the domain entity model, so that for the user, by invoking the storage object, the user can directly get the data they want without having to care about how the data is coming. We can compare warehousing to a supermarket, supermarkets have been ready for the consumer goods, consumers just go to the supermarket to buy their own products, and do not have to care about these goods from which suppliers how to transport to the supermarket. But for the warehousing itself, it is necessary to realize the "channel" to read the data.

Add a folder named concrete to the Bookshop.domain project to hold the specific class. We add a Bookrepository class that implements the Ibookrepository interface in the concrete folder as our book Data warehousing. The Bookrepository class code is as follows:

public class Bookrepository:ibookrepository {public    iqueryable<book> Books {        get {return getbooks (). AsQueryable (); }    }    private static list<book> Getbooks () {          //For demonstration purposes, some data are created here, followed by the use of EF to read from the database.        list<book> books = new list<book>{            new book {ID = 1, Title = "ASP. NET MVC 4 Programming", Price =--},            NE W Book {id = 2, title = "CLR Via C #", Price = n},            new book {id = 3, title = "Ordinary World", Price = Notoginseng}        };        return books;}    }

To illustrate, there are some handmade data, and later articles I'll cover using entity framwork to read data from the database. For a friend who has just touched the ORM framework, it might be strange to IQueryable here, why use IQueryable as the return type instead of IEnumerable? There is a chance to talk about the entity Framwork later.

Adding bindings

Open the Ninjectcontrollerfactory class that we created earlier in the Bookshop.webui project, and add the following code to the Addbindings method

private void Addbindings () {    ninjectkernel.bind<ibookrepository> (). To<bookrepository> ();}

This code, through Ninject, binds the Ibookrepository interface to Bookrepository, and Ninject automatically creates an instance of the Bookrepository class when the implementation of the Ibookrepository interface is requested.

Here, the use of ninject is over, and we'll finish with the rest of this example.


Display list

Right-click the Controllers folder for the Bookshop.webui project, add a controller named book, and edit it as follows:

public class Bookcontroller:controller {    private ibookrepository repository;    Public Bookcontroller (Ibookrepository bookrepository) {        repository = bookrepository;    }}

In this case, the Bookcontroller constructor accepts a ibookrepository parameter, and when Bookcontroller is instantiated, Ninject injects a bookrepository dependency on it. Next we add an action named List to this controller, which is used to render the book list. The code is as follows:

public class Bookcontroller:controller {    ...    Public ViewResult List () {        return View (repository. Books);}    }

Of course we need to add a view. Right click on the list method above, select Add View, in the popup window to configure the following:

We then use the Foreach Loop in list.cshtml to enumerate the book information, which is the following code:

@model ienumerable<bookshop.domain.entities.book>@{    viewbag.title = "Books";} @foreach (var p in Model) {      <div class= "item" style= "border-bottom:1px dashed silver;" >         

Finally we need to modify the default route, let the system run directly to our {controller = "book", action = "List"}, open the Global.asax file, find the RegisterRoutes method, make the following changes:

public static void RegisterRoutes (RouteCollection routes) {    routes. Ignoreroute ("{resource}.axd/{*pathinfo}");    Routes. MapRoute (        "Default",//Route name         "{controller}/{action}/{id}",//URL with parameters         New {controller = "B Ook ", action =" List ", id = urlparameter.optional}    );}

To this, our program can be run, the effect is as follows:

Conclusion:

This article is a simple example of ninject used in ASP. NET MVC, which is intended to give you an idea of how ninject is used in MVC. Of course, the power of Ninject is not limited to what this article demonstrates, and I believe that when you become familiar with Niject, you will love it when building an MVC application.

The above is [ASP.]05-Use ninject content, more about topic.alibabacloud.com (www.php.cn)!

  • 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.