Using Ninject injection in. NET MVC is mainly divided into the following steps:
- Using the NuGet package to add the Ninject reference, I added the current version 3.34
- Under the App_start folder, create the Ninjectcontrollerfactory class
- Add the following code to global
- The main use of the project is interface injection, can refer to the Iuser invocation example
Public classNinjectcontrollerfactory:defaultcontrollerfactory {PrivateIkernel Kernel; Publicninjectcontrollerfactory () {Kernel=NewStandardkernel (); Addbindings (); } protected OverrideIController getcontrollerinstance (RequestContext requestcontext, Type controllertype) {returnControllertype = =NULL?NULL: (IController) Kernel.get (Controllertype); } Private voidaddbindings () {Kernel.bind<IUser> (). To<user>(); } Public ObjectGetService (Type servicetype) {return This. Kernel.tryget (servicetype); } Publicienumerable<Object>getservices (Type servicetype) {return This. Kernel.getall (servicetype); } }
protected void Application_Start () {log4net. Config.XmlConfigurator.Configure (); // set up controller factory ControllerBuilder.Current.SetControllerFactory (new ninjectcontrollerfactory ()); Arearegistration.registerallareas (); Filterconfig.registerglobalfilters (globalfilters.filters); Routeconfig.registerroutes (routetable.routes); Bundleconfig.registerbundles (Bundletable.bundles); }
Public class Homecontroller:controller { [ninject.inject] publicgetset;} [Allowlogin] Public ActionResult Login (string UserName,string userpwd) { var Usermodel = user. Getbylogin (UserName,userpwd
}
Using Ninject Dependency Injection in MVC