This article is a mirror article of machine translation, please click here to jump to the original article.

View: 14932|Reply: 0

[ASP.NET] asp.net MVC uses ninject to implement IOC dependency injection

[Copy link]
Posted on 10/14/2016 4:46:57 PM | | |
First, install the Ninject framework with the following Nuget command:



Create an interface:



Then implement this interface:



We create a folder called Infrastructure under the WebUI project, add a factory class called NinjectControllerFactory to it, the code is as follows:



ninjectKernel.Get(controllerType) in the above code can get a Controller instance. If manually instantiating the Controller class is a very complicated process, we don't know if the Controller class has a constructor with parameters, or what type of argument the constructor is. To use Ninject, you only need to use one of the above Get methods, and Ninject will automatically handle all dependencies internally and intelligently create the objects we need.

Once the Controller Factory class is created, we need to tell MVC to use our NinjectControllerFactory class to create the Controller object, to do this, we need to add the following code to the Application_Start method of the Global.asax file:




We create a new class called ControllerBase in the controller folder, and the code is as follows:



Then, we modify the controller to integrate the ControllerBase class, ok, done!






Previous:c# Calculate the SHA256 value of the file
Next:Install VSFTP process organization
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com