Preface

Ninject Is an open source lightweight dependency injection plug-in . From the contact ioc since , Always use this , I think it's good to use , It's easy to configure . stay mvc It's a basic fool like configuration .

Preparation before development

  1. Create a new one mvc3 project .
  2. install Ninject.mvc3. This is the birth control center ninject stay mvc3 An extension of . Can be directly in nuget Install in . Here's the picture :

After the search , Click Install to your own project layer ( I have only one floor here , So install it directly to the root of the website ), So a folder will appear in the project App_Start There is a cs file , yes ninject.mvc3 This plug-in is written for me ioc class .

So we configure the environment , It's time to start the development of dependency injection .

Development

  1. Create a new interface class ITest:
 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5
6 namespace MvcIoc.Interface
7 {
8 public interface ITest
9 {
10 string GetMsg(string str);
11
12 }
13 }

2. Create a new class Test, Realization ITest Interface

 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using MvcIoc.Interface;
6
7 namespace MvcIoc.Concrete
8 {
9 public class Test:ITest
10 {
11 public string GetMsg(string str)
12 {
13 return " Dependency injection test message :" + str;
14 }
15 }
16 }

3. Open our installation Ninject.mvc3 When App_Start Automatically created under cs class . In the code Itest and Test binding . The code is as follows :

[assembly: WebActivator.PreApplicationStartMethod(typeof(MvcIoc.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(MvcIoc.App_Start.NinjectWebCommon), "Stop")] namespace MvcIoc.App_Start
{
using System;
using System.Web; using Microsoft.Web.Infrastructure.DynamicModuleHelper; using Ninject;
using Ninject.Web.Common;
using MvcIoc.Interface;
using MvcIoc.Concrete;
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper(); /// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
} /// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
bootstrapper.ShutDown();
} /// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); RegisterServices(kernel);
return kernel;
} /// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
// All interface and implementation class bindings are written here
kernel.Bind<ITest>().To<Test>();
}
}
}

In this way, we bind an interface to a class that implements the interface .

4. Create a new one HomeController, And then write a Index Of action, And create index The view of . And give the interface in the constructor Itest Initialize an object .

 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.Mvc;
6 using MvcIoc.Interface;
7 namespace MvcIoc.Controllers
8 {
9 public class HomeController : Controller
10 {
11 //
12 // GET: /Home/
13
14 public ITest test;// Define the interface to be called during constructor initialization .
15 public HomeController(ITest test)
16 {
17 this.test = test;
18 }
19
20 public ActionResult Index()
21 {
22 ViewBag.test = test.GetMsg(" Test success ");
23 return View();
24 }
25
26 }
27 }

And then the view code : Display the called... On the page GetMsg Returned message .

1 @{
2 ViewBag.Title = "Index";
3 }
4
5 <h2>Index</h2>
6 @ViewBag.test

5. Such a dependency injection project is complete , Run code . give the result as follows :

Project code

Download this

Ninject stay mvc More articles on simple configuration in

  1. SpringSecurity stay MVC Simple use of ( Translated , A little change )

    Spring Security Allows developers to easily integrate security features into J2EE Web In the application , It passes through Servlet Filter implementation “ User customization ” security check . In this tutorial , We're going to show you how to Spring MVC ...

  2. stay ASP.NET Core MVC It's easy to build in Web Api

    Getting Started stay ASP.NET Core MVC In the frame ,ASP.NET The team provided us with a complete set of tools to build a Web The kits required for the various parts of , So sometimes we just need to do a simple ...

  3. axios stay vue Simple configuration and use of

    One .axios brief introduction axios It's based on Promise For browsers and nodejs Of HTTP client , It has the following characteristics :https://hzzly.github.io/2017/03/12/ ...

  4. asp.net mvc The construction of simple project framework ( Two )—— Spring.Net stay Mvc Simple application in

    Abstract : The first part describes how to build a simple project framework , About Dal and Bll Knowledge of decoupling between , After this article i Let's talk about the noodles . The first part talks about DbSession, Now let's move on . First , I'd like to perfect some similar operations ...

  5. log4net stay Asp.net Mvc Application configuration and introduction in

    log4net stay .NET The position in the world is not much , This article focuses on configuration . Less introduction to the use of . Because on the Internet, you can search hundreds of thousands of articles on the Internet to tell you how to use . There's no nonsense about installation , It's simple .Nuget Search inside "log4n ...

  6. spring MVC in Dubbo Configuration of

    1. Service provider's bubbo To configure : <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi=& ...

  7. spring mvc Interceptor configuration in mvc:interceptors

    Actually in mvc:interceptors In the label , There are two types of configuration , One directly configures a bean(bean and ref Classed ), The other is to configure the intercepted path and the excluded path . Directly configured bean That's for all requests ...

  8. spring mvc in web.xml Configuration information interpretation

    There are always some loading priority issues in projects , I've also encountered similar problems recently , So I look up the information and sum up , Some of the following are reprinted from others , After all, it's well written , I don't want to make wheels myself , Just a little bit of their own embellishment . The first thing is for sure ...

  9. spring mvc in controller Path configuration

    The following figure , Because of the red part (value="/") The existence of , Lead to  host:port/ project /dimlist Cannot be mapped to dimList Method , The solution is to get rid of it . package cn.bgo ...

Random recommendation

  1. MVC To get the metadata of a member in Description Feature description information common method

    #region Gets the specified... From a type member Attribute T Property set /// <summary> /// Gets the specified... From a type member Attribute T Property set /// </summary ...

  2. checkpoint (Checkpoint) How the process handles uncommitted transactions

    Every time I explain SQL Server Before , I'll talk about it briefly first. When we execute a query , stay SQL Server What happened inside . Execute one SELECT The sentence is very simple , But to perform DML The statement is more complex , because SQL Server To be modified ...

  3. uC/OS-II Application code

    /*************************************************************************************************** ...

  4. POJ1329 topic

    Circle Through Three Points Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 20000/10000K (Jav ...

  5. 2, return Json

    One , Use Spring Boot Default Json Analytical framework jackson 1, Create an entity class Persion package com.zh.json; public class Persion { privat ...

  6. Cross domain WebApi Of Jquery EasyUI Data interaction

    Catalog 1       General idea ... 1 2       establish WebAPI 1 3       establish CrossMainController And write ... 1 4       Nuget install microso ...

  7. vue echarts map Use , Page multi graph dynamic adaptive

    Recently vue Use in echarts when , I met some pits , Record here . 1:echarts map Use 2: Page multi graph adaptive , Only one diagram works 3: According to the dpr, Dynamically modified meta In the tag initial ...

  8. kali linux networking scanning Cookbok ( The third chapter concludes with notes )

    1.Zombie Scanning with Nmap Zombie scans can also be performed with an option in Namp ,  we can find ...

  9. 51Nod 1022 Stone merge V2( Section DP+ Quadrilateral optimization )

    Topic link :http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1022 The main idea of the topic : N Make a circle of stones . Now we are going to merge the stones into ...

  10. ubuntu Lower installation configuration apache2( Including virtual host configuration )

    stay Ubuntu14.14 Install in apache Installation instructions : sudo apt-get install apache2 After installation : The generated start and stop files are : /etc/init.d/apache2 start-up : ...