Project Structure diagram:
The files in the App_start folder are created by vs itself, where the Ninjectwebcommon class does not exist at the beginning of creation. It will be mentioned again later!
Add a home controller. The code is as follows:
usingEssentialtools.models;usingNinject;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSYSTEM.WEB.MVC;namespaceessentialtools.controllers{ Public classHomecontroller:controller {PrivateIvaluecalculator Calc; Product[] Products={ NewProduct{name="Kayak", category="Watersports", price=275M},NewProduct{name="lifejacket", category="Watersports", price=48.95M}, NewProduct{name="Soccer Ball", category="Soccer", price=19.50M}, NewProduct{name="Corner Flag", category="Soccer", price=34.95M} }; PublicHomeController (Ivaluecalculator calcparam) {Calc=Calcparam; } PublicActionResult Index () {//Ikernel Ninjectkernel = new Standardkernel (); //ninjectkernel.bind<ivaluecalculator> (). To<linqvaluecalculator> (); //Linqvaluecalculator calc = new Linqvaluecalculator (); //return View (Calc. Valueproducts (Products));ShoppingCart cart =NewShoppingCart (Calc) {products =Products }; decimalTotalvalue =cart. Calculateproducttotal (); returnView (Totalvalue); } }}
HomeController.cs
Add a view for the index method in the controller. The code is as follows:
@model decimal@{ viewbag.title = "Index"; Layout = null;} < Div > Total value is [email protected]</div>
index.cshtml
Create a infrastructure folder under which to create the Ninject dependent parser. The code is as follows:
usingEssentialtools.models;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSYSTEM.WEB.MVC;usingNinject;namespaceessentialtools.infrastructure{ Public classNinjectdependencyresolver:idependencyresolver {PrivateIkernel kernel; Publicninjectdependencyresolver (Ikernel knernelparam) {kernel=Knernelparam; Addbindings (); } Public ObjectGetService (Type servicetype) {returnkernel. Tryget (servicetype); } Publicienumerable<Object>getservices (Type servicetype) {returnkernel. GetAll (servicetype); } Private voidaddbindings () {kernel. Bind<IValueCalculator> (). To<linqvaluecalculator>(); } }}
NinjectDependencyResolver.cs
Save the key 1 interfaces in the Models folder, 3 classes. The code is as follows:
using System; using System.Collections.Generic; using System.Linq; using system.web; namespace essentialtools.models{ publicinterface ivaluecalculator { decimal valueproducts (ienumerable<product> products );} }
IValueCalculator.cs
using System; using System.Collections.Generic; using System.Linq; using system.web; namespace essentialtools.models{ public class Linqvaluecalculator:ivaluecalculator {
public
decimal valueproducts (ienumerable< Product>
products) {
return p Roducts. Sum (P =>
P.price); } }}
LinqValueCalculator.cs
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;namespaceessentialtools.models{ Public classProduct { Public intProductID {Get;Set; } Public stringName {Get;Set; } Public stringDescription {Get;Set; } Public decimalPrice {Get;Set; } Public stringCategory {Get;Set; } }}
Product.cs
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;namespaceessentialtools.models{ Public classShoppingCart {Ivaluecalculator calc; PublicShoppingCart (Ivaluecalculator calcparam) {Calc=Calcparam; } PublicIenumerable<product> Products {Get;Set; } Public decimalcalculateproducttotal () {returnCalc. Valueproducts (products); } }}
ShoppingCart.cs
Installing Ninject with NuGet
Tools → library Package Manager → Package Manager console
To install the Ninject kernel package:
Install-package ninject-version 3.0.1.10
Install the Ninject Kernel Pack expansion pack:
Install-package ninject.web.common-version 3.0.0.7
References to MVC3 (still available in mvc5)
Install-package ninject.mvc3-version 3.0.0.6
The version number is best to bring with you, without the version number, which can be an error!
The NinjectWebCommon.cs file will appear after the installation is ready. You need to add code for the Registerservices method in the class (registering a dependent parser)
The Registerservices method code is as follows:
Private Static void registerservices (ikernel kernel) { System.Web.Mvc.DependencyResolver.SetResolver ( new EssentialTools.Infrastructure.NinjectDependencyResolver (kernel)); }
Registerservices Method Code
What happens when the browser makes a request to the controller to process the request!
1. The browser sends a request to the MVC framework The URL,MVC framework of the home speculates that the request means the home controller and creates an instance of the HomeController class.
2. The MVC framework discovers that its constructor has a dependency on the Ivaluecalculator interface during the creation of the HomeController class instance, and therefore requires the dependency resolver to parse the dependency. Specifies the interface as the type parameter used by the GetService method in the dependency resolver.
3. The dependency resolver will hand over the passed type parameter to the Tryget method, requiring Ninject to create a new HomeController interface instance.
4. Ninect detects that the HomeController constructor has a binding relationship with its implementation class Lilnqvaluecalculator, then creates an instance of the Linqvaluecalculator class for the interface and passes it back to the dependency resolver.
5. The dependency resolver recursively ninject the Lilnqvaluecalculator class returned as Ivaluecalculator interface implementation class instance to the MVC framework
6. The MVC framework creates an HomeController controller instance using an instance of the interface class returned by the dependency resolver and uses the controller instance to service the request.
Using Ninject in an MVC project