Contact Ninject This IOC tool from the MVC3. It has also been the recommended IOC tool in the MVC Framework series and, of course, excellent AUTOFAC. Performance and use of the above has a lifetime. Let's take a look at the use of Ninject:
1. Add Ninject. Tools-->nuget Package Manager, and Package Manager console, enter the following command:
Install-package ninject-version 3.0.1.10install-package ninject.web.common-version 3.0.0.7install-package Ninject.mvc3-version 3.0.0.6
2. Create a dependent ninjectdependencyresolver.
Ninjectdependencyresolver implements the Idependencyresolver interface, and when a request comes in, the MVC framework invokes the GetService or GetServices method to fetch an instance of the object to serve the request. The GetAll method supports multiple bindings of a single type. We add bindings for the interface in the Addbinds method.
Public classNinjectdependencyresolver:idependencyresolver {PrivateIkernel kernel; Publicninjectdependencyresolver (Ikernel kernelparam) {kernel=Kernelparam; Addbindings (); } Public ObjectGetService (Type servicetype) {returnkernel. Tryget (servicetype); } Publicienumerable<Object>getservices (Type servicetype) {returnkernel. GetAll (servicetype); } Private void addbindings() {
Kernel. Bind<iproductrepository> (). To<efproductrepository> ();
Kernel. Bind<iauthprovider> (). To<formsauthprovider> ();
} }
3. Registration
In mvc3,4, we are registered in the Application_Start () of global. The method in Application_Start () is triggered back when the app starts.
Dependencyresolver.setresolver (new ninjectdependencyresolver ());
That again MVC5 in, more perfect. Notice that we quoted Ninject.Web.Common earlier, which was not played before MVC4. It creates a NinjectWebCommon.cs class in the App_start file:
Its Start method is performed prior to the global Application_Start () method.
[Assembly:WebActivator.PreApplicationStartMethod (typeof(Ninjectwebcommon),"Start")][assembly:webactivator.applicationshutdownmethodattribute (typeof(Ninjectwebcommon),"Stop")]namespacesportsstore.webui{ Public Static classNinjectwebcommon {Private Static ReadOnlyBootstrapper Bootstrapper =NewBootstrapper (); /// <summary> ///starts the application/// </summary> Public Static voidStart () {Dynamicmoduleutility.registermodule (typeof(Oneperrequesthttpmodule)); Dynamicmoduleutility.registermodule (typeof(Ninjecthttpmodule)); Bootstrapper. Initialize (Createkernel); } /// <summary> ///Stops the application. /// </summary> Public Static voidStop () {bootstrapper. ShutDown (); } /// <summary> ///creates the kernel that would manage your application. /// </summary> /// <returns>The created kernel.</returns> Private StaticIkernel Createkernel () {varKernel =NewStandardkernel (); Kernel. Bind<Func<IKernel>> (). Tomethod (CTX = () =NewBootstrapper (). Kernel); Kernel. Bind<IHttpModule> (). To(); Registerservices (kernel); returnkernel; } /// <summary> ///Load your modules or register your services here! /// </summary> /// <param name= "kernel" >The kernel.</param> Private Static voidregisterservices (Ikernel kernel) {System.Web.Mvc.DependencyResolver.SetResolver (NewInfrastructure. Ninjectdependencyresolver (kernel)); } }}
It takes full advantage of the new technology of ASP. Webactivator Framework , calls the start function dynamically before the Web program starts, and calls the Stop function before closing. In the start function, Oneperrequesthttpmodule and Ninjecthttpmodule are registered dynamically. For the Createkernel function, the IOC core is created first, and then the func<ikernel> is bound. Type and IHttpModule type.
5. Binding method:
1) Basic binding
Kernel. Bind<ivaluecalculator> (). To<linqvaluecalculator> ();
2) Pass Parameters:
Create a Idiscounthelper interface. Let Defaultdiscounthelper implement it.
Public InterfaceIdiscounthelper {decimalApplyDiscount (decimaltotalparam);} Public classDefaultdiscounthelper:idiscounthelper { Public decimaldiscountsize {Get;Set; } Public decimalApplyDiscount (decimalTotalparam) {return(Totalparam-(discountsize/100m *totalparam));}
View Code
Kernel. Bind<idiscounthelper>(). to <DefaultDiscountHelper> (). Withpropertyvalue ("discountsize", 50M);
You can also pass parameters from the constructor:
public class Defaultdiscounthelper:idiscounthelper { decimal discountsize; public defaultdiscounthelper (decimal Discountparam) { Discountsize = Discountparam;} public decimal ApplyDiscount (decimal Totalparam) { Span style= "color: #0000ff;" >return (Totalparam-(discountsize/100m * Totalparam))}}
Kernel. Bind<idiscounthelper>(). to <DefaultDiscountHelper> (). withconstructorargument ("discountparam", 50M);
3) Conditional binding
Sometimes we have an interface that has different implementation objects. At this point we need to get the corresponding instance according to the usage situation. Let's create a flexiblediscounthelper to implement the above interface.
Public class flexiblediscounthelper:idiscounthelper {publicdecimal applydiscount (decimal Totalparam) {decimal; return (Totalparam-(discount/100m * totalparam));}}
Kernel. Bind<idiscounthelper> (). To<flexiblediscounthelper>(). Wheninjectedinto<LinqValueCalculator> ();
The above means: when injected into the Linqvaluecalculator, bind Flexiblediscounthelper. This is much more convenient.
Method |
Effect |
When (predicate) |
Use this binding when the lambda expression result is ture |
Whenclasshas<t> () |
The binding is used when the injected object is marked with the attribute T |
Wheninjectedinto<t> () |
The binding is used when the injected object is T. |
4) Scope of action
Kernel. Bind<ivaluecalculator> (). To<linqvaluecalculator> (). Inrequestscope ();
Inrequestscope is an extension method in the Ninject.Web.Common namespace that tells Ninject that only one linqvaluecalculator instance should be created for each HTTP request that is received by ASP.
Method |
Effect |
Intransientscope () |
The default mode, which will create a new instance when each dependency is resolved. |
Insingletonscope () |
Single-case mode, throughout the application. |
Toconstant (object) |
Binds to a constant light. |
Inthreadscope () |
Create a single instance for a single thread |
Inrequestscope () |
Create a single instance for a single HTTP request
|
Here is a description of the next toconstant, for an interface, we implemented a good object, you can use the Toconstant method to bind
For example, we implemented interface iproductrepository with MOQ, so that in the case where this interface is used, the injected instance already contains three product objects, which is equivalent to being initialized.
varmock=NewMock<iproductrepository>(); Mock. Setup (M= m.products). Returns (NewList<product> { NewProduct {Name ="Football", Price = -}, NewProduct {Name ="Surf Board", Price =179}, NewProduct {Name ="Running Shoes", Price = the} }); Kernel. Bind<iproductrepository> ().toconstant(mock.) Object);
Summary: IOC has many applications in MVC, and it is necessary to choose an IOC framework that suits your needs. I hope this article will be of help to you.
Reference article: NinJect Source Analysis: http://www.verydemo.com/demo_c360_i40786.html
IOC Framework Performance Comparison: http://www.cnblogs.com/liping13599168/archive/2011/07/17/2108734.html
The Calf road ninject:http://www.cnblogs.com/willick/p/3299077.html
Read books: Apress Pro ASP. MVC5
The use of "reading notes" Ninject in MVC5