ASP. NET mvc3 + ninject. mvc3 dependency injection can be so simple

Source: Internet
Author: User

Not written for a long timeArticleIt's lazy.

Today, I received an email calledHmqMy colleagues raised questions about ASP. NET mvc3 dependency injection,

At that time, when I wrote this article, the official mvc3 version was not available yet. At that time, I used the mvc3 beta version, and now mvc4 is coming soon,

Therefore, this demo was successfully tested in the current environment and there was no problem, but there may be problems in the current environment (I have not tested it ),

If there is time in the day, I will take this demo and make appropriate modifications to make it suitable for the current mvc3 version. However, I don't think it is necessary,

Because it is very easy to use dependency injection in ASP. NET mvc3, there are few linesCodeTo implement dependency injection, ninject is recommended,

The procedure is as follows:

 

Step 1: Create an ASP. NET mvc3 project.

Step 2: PassNugetEnter the following command in the console:Install-package ninject. mvc3

After installing the source code package, all the dependency injection frameworks have been set up, so you do not need to change any code,

You will find that a "app_start" folder is added to the project, and a code file named "ninjectmvc3.cs" is generated in this folder.

Step 3. Open \ app_start \ ninjectmvc3.cs and findRegisterservicesMethod to directly write your dependency injection ing code.

 

The code list is as follows:

Automatically Generated \ app_start \ ninjectmvc3.cs code:

[Assembly: webactivator. preapplicationstartmethod ( Typeof (Mvcapplication3.app _ start. ninjectmvc3 ), " Start " )]
[Assembly: webactivator. applicationshutdownmethodattribute ( Typeof (Mvcapplication3.app _ start. ninjectmvc3 ), " Stop " )]

NamespaceMvcapplication3.app _ start
{
UsingSystem. reflection;
UsingMicrosoft. Web. Infrastructure. dynamicmodulehelper;
UsingNinject;
UsingNinject. Web. MVC;
UsingMvcapplication3.services;
{

Public Static ClassNinjectmvc3
Private Static ReadonlyBootstrapper =NewBootstrapper ();

///   <Summary>
/// Starts the application
///   </Summary>
Public Static Void Start ()
{
Dynamicmoduleutility. registermodule ( Typeof (Oneperrequestmodule ));
Dynamicmoduleutility. registermodule ( Typeof (Httpapplicationinitializationmodule ));
Bootstrapper. initialize (createkernel );
}

///   <Summary>
/// Stops the application.
///   </Summary>
Public Static Void Stop ()
{
Bootstrapper. Shutdown ();
}

///   <Summary>
/// Creates the kernel that will manage your application.
///   </Summary>
///   <Returns> The created kernel. </Returns>
Private Static Ikernel createkernel ()
{
VaR Kernel = New Standardkernel ();
Registerservices (kernel );
Return Kernel;
}

///   <Summary>
/// Load your modules or register your services here!
///   </Summary>
///   <Param name = "kernel"> The kernel. </Param>
Private Static Void Registerservices (ikernel kernel)
{
// Write the dependency injection relationships you need to bind. Other Code except this method is automatically generated, so we don't have to worry about it.

// The bug was fixed in 2011-10-26 and the inrequestscope () was missing. This is very important!

// ThanksScott XuError , Almost mistaken!

 

Kernel. Bind <itestservice> (). To <testservice> (). inrequestscope ();

}
}
}

 

The test code is as follows:

\ Services \ itestservice. CS

Namespace Mvcapplication3.services
{
Public Interface Itestservice
{
String Getmessage ( String Astring );
}
}  

 

\ Services \ testservice. CS

Using System;

Namespace Mvcapplication3.services
{
Public Class Testservice: itestservice
{
String Itestservice. getmessage (String Astring)
{
Return " -------------- " + (String. isnullorempty (astring )? String. Empty: astring) + " -------------- " ;
}
}
}

 

\ Controllers \ homecontroller. CS

Using System. Web. MVC;
Using Ninject;
Using Mvcapplication3.services;

NamespaceMvcapplication3.controllers
{
Public ClassHomecontroller: Controller
{

[Inject]
PublicItestservice Service {Get;Set;}

PublicActionresult index ()
{
Viewbag. Message = service. getmessage ("Welcome to ASP. net mvc!");
ReturnView ();
}

PublicActionresult about ()
{
ReturnView ();
}

}
}

 

On this basis, we can perform some optimizations on our own to make it easier to use dependency injection and be more suitable for team development,

Just say a wordNugetIt's really good. You should make good use of it.

Download the source code: ninect.mvc3_demo.zip (Environment: vs2010 SP1 + mvc3)

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.