Using Ninject Dependency Injection in MVC

Source: Internet
Author: User

Using Ninject injection in. NET MVC is mainly divided into the following steps:

    1. Using the NuGet package to add the Ninject reference, I added the current version 3.34
    2. Under the App_start folder, create the Ninjectcontrollerfactory class
    3. Add the following code to global
    4. 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

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.