Use ninject in ASP. NET mvc4

Source: Internet
Author: User

Ninject is a fast and lightweight dependency injection framework based on the. NET platform. It can help you applyProgramThe modules are separated into loosely coupled and highly cohesive modules, and then assembled in a flexible manner. By using ninject to match your software architectureCodeIt will become easier to write, reusable, and easy to test and modify.

Mvc4 and ninject 3 are even more powerful.

1. Problem scenarios

In MVC development, we usually use background data. For example, we need to obtain background information. Generally, an interface for access information is defined, and a class implements this interface.

Public InterfaceImessageprovider {StringGetmessage ();}Public ClassNinjectmessageprovider: imessageprovider {Public StringGetmessage (){Return "This message was provided by ninject";}}

Such code often appears in the controller.

 Public   Class Homecontroller: controller {  Private Imessageprovider messageprovider { Set ; Get  ;}  Public  Homecontroller (){  This . Messageprovider = New  Ninjectmessageprovider ();}  Public  Actionresult index (){  String Message =This  . Messageprovider. getmessage ();  Return View (( Object  ) Message );}......} 

Here, the constructor is used to create the providers' object instance. The problem is that there will be a large number of controllers on the website. Therefore, we need to write such code in each controller, if the type of the provider object to be created in the future is no longerNinjectmessageproviderType will cause a lot of modifications.

Using ninject can solve these problems.

2. Get ninject

: Http://www.ninject.org/

The first method is commonly used to reference an assembly. First, download it from the official website. Note that there are multiple versions.

After decompression, you will get an Assembly named ninject. dll and reference it to your project.

Another method is to use nuget supported by Visual Studio. This tool can help you download the corresponding Assembly from the Internet and reference it to the project.

3. Easy to use

First, open the Controller code file and use using to reference the ninject namespace. The extension method is used here.

 
UsingNinject;

Then, modify the constructor as follows:

 
PublicHomecontroller () {ninject. ikernel ninjectkernel=NewNinject. standardkernel (); ninjectkernel. Bind<Imessageprovider>().<Ninjectmessageprovider>();This. Messageprovider = ninjectkernel. Get <imessageprovider>();}
 
Ninject. ikernel is the core of ninject.

4. Use dependency Injection

In each controller, it is not as convenient to create objects like this. Fortunately, MVC provides the dependency injection entry. We can modify the current constructor to support constructor injection.

PublicHomecontroller (imessageprovider provider ){This. Messageprovider =Provider ;}

Create a ninjectdependencyresolver to implement the injection interface provided in MVC.Idependencyresolver, As shown below.

 Using  System;  Using  System. Collections. Generic;  Using  System. LINQ;  Using  System. Web;  Using  Ninject; Using  Mvcapplication1.controllers;  Namespace  Mvcapplication1 {  Public   Class  Ninjectdependencyresolver: system. Web. MVC. idependencyresolver {  Private  Ninject. ikernel kernel;  Public  Ninjectdependencyresolver (){  This . Kernel = New Ninject. standardkernel ();  This  . Addbindings ();}  Private   Void  Addbindings (){  This . Kernel. Bind <imessageprovider> (). <Ninjectmessageprovider> ();}  Public   Object  Getservice (type servicetype ){  Return  This  . Kernel. tryget (servicetype );}  Public Ienumerable < Object > Getservices (type servicetype ){  Return   This  . Kernel. getall (servicetype );}}} 

Do not forget to register this container in step 3. Add the following code to global. asax.

System. Web. MVC. dependencyresolver. setresolver (NewEvents (); arearegistration. Events (); webapiconfig. Register (globalconfiguration. configuration); filterconfig. registerglobalfilters (globalfilters. filters); routeconfig. registerroutes (routetable. routes );

Run the program again and you will find that the controller can directly obtain the message provider object.

When MVC acquires the Controller object, it finds that an object instance that implements the interface imessageprovider needs to be passed to the constructor. ninject finds that the registered type is ninjectmessageprovider, ninject will automatically help us create an object instance, and then pass this object instance to the Controller.

5. Use property Injection

What if the Controller uses attribute injection instead of constructor injection? There is no problem at all. You only need to mark a feature. Note: The scope of this attribute must be public.

 
[Ninject. Inject]PublicImessageprovider messageprovider {Set;Get;}

What? Is your member private? No problem. Set it so that ninject can be injected into non-public members.

 
PublicNinjectdependencyresolver (){This. Kernel =NewNinject. standardkernel ();This. Kernel. settings.Injectnonpublic =True;This. Addbindings ();}

In this way, the following members can also be injected.

 
[Ninject. Inject]PrivateImessageprovider messageprovider {Set;Get;}

 

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.