Using Ninject for Dependency injection in MVC

Source: Internet
Author: User

When it comes to dependency injection, the first thing to mention is control inversion, control reversal (inversion of controls, English abbreviation for IOC) is an important object-oriented programming principle that aims to reduce the coupling problem of computer programs control inversion is generally divided into two types,

Dependency Injection (Dependency injection, abbreviation DI) and dependent lookups. The difference between the two is that the former is a passive receiving object, and a dependent B object is created during instance creation of Class A, by type or name to determine the injection of different objects into different

property, which is an object that proactively requests a response name, and the time it takes to obtain a dependent object can be freely controlled in the code. But the application of dependency injection is quite extensive. An important feature of MVC is the separation of concerns (separation of concerns). of the application

each component should be as independent as possible, with as few interdependencies as possible, and the article about dependency injection is a lot more in the garden, such as the dependency of T2 bacteriophages .

Dependency Injection is implemented in the following way: based on the interface. Implements a specific interface for an external container to inject an object of the dependent type. based on the set method. The public set method that implements a specific property lets the outer container invoke an object that is passed in to the dependent type. based on the constructor function. A constructor that implements a specific parameter, passing in an object of the dependent type when a new object is created.

NET platform, there are many excellent IOC frameworks such as: Ninject,spring.net,objectbuilder,structuremap,castleproject,seasar and so on.

At the moment I'm studying the MVC phase, I only touch ninject, and the following code is written based on this framework.

First Use VS2012 nuget to download the installation Ninject

Add the Ninjectcontrollerfactory class to your project as follows:

 Public classNinjectcontrollerfactory:defaultcontrollerfactory {PrivateIkernel Ninjectkernel;  Publicninjectcontrollerfactory () {Ninjectkernel=NewStandardkernel ();        Addbindings (); }        protected OverrideIController getcontrollerinstance (RequestContext requestcontext, Type controllertype) {returnControllertype = =NULL?NULL: (IController) Ninjectkernel.get (Controllertype); }        Private voidaddbindings () {//TODO: Add bindings later                               }    }

Use the repository mode to decouple the domain model from the customer code and the data mapping layer.

Create a common Storage interface irepository

 Public Interface where class     {        IQueryableget;}    }

To create a model class

 Public classBook { Public intID {Get;Set; }  Public stringTitle {Get;Set; }  Public stringISBN {Get;Set; }  Public stringSummary {Get;Set; }  Public stringAuthor {Get;Set; }  Public byte[] Thumbnail {Get;Set; }  Public decimalPrice {Get;Set; }  PublicDateTime Published {Get;Set; } }

Create a bookrepository<book> that implements the Irepository<t> interface

  PublicIqueryable<book> Lists {Get{returngetbooks (). AsQueryable (); } }        Private StaticList<book>Getbooks () {//to demonstrate, some data is created here, which is later described using EF to read from the database. list<book> books =NewList<book>{           NewBook {ID =1, Title ="ASP. NET MVC 4 programming", Price = the},          NewBook {ID =2, Title ="CLR Via C #", Price = $},          NewBook {ID =3, Title ="the Ordinary World", Price =Panax Notoginseng}        }; returnBooks; }

Next, modify the Addbindings () method of the preceding Ninjectcontrollerfactory class

Private void addbindings ()        {            //  TODO: Add bindings                         ninjectkernel.bind<IRepository<Book>>) later. To<bookrepository>();        }

So Ninject will automatically help us create instances of the classes we need.

We need to register the Ninjectcontrollerfactory class in the Global.asax file

protected void Application_Start ()        {            .            .            .            . ControllerBuilder.Current.SetControllerFactory (new ninjectcontrollerfactory ()); // register Ninjectcontrollerfactory class        }

Creating a Bookcontroller Controller

 Public classBookcontroller:controller {//        //GET:/book/        PrivateIrepository<book>bookrepository;  PublicBookcontroller (irepository<book> bookrepository, irepository<author>authorepository) {             This. Bookrepository =bookrepository;  This. Authorepository =authorepository; }         PublicActionResult Index () {returnView (); }                 PublicViewResult Booklist () {returnView (bookrepository.        Lists); }           }

Create Booklist View page code as follows

@model iqueryable<bookshopdomain.book>@{Viewbag.title="Booklist";} @Html. Action ("View1")@foreach (varBookinchModel) {    <divclass="Item"style="border-bottom:1px dashed silver;"> "C") </p> </div> }

Open the browser and enter an address in the address bar to run the program successfully:

A simple MVC Dependency injection program is complete. Here I simply use the ninject, still need to continue to study.

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.