1.安装Ninject
2.使用Ninject
一 安装Ninject
Nuget:Ninject
二 使用Ninject
public interface IStudent { string GetName(); }
public class Student : IStudent { public string GetName() { return "ligenyun"; } }
public class NinjectControllerFactory : DefaultControllerFactory { private IKernel ninjectKernel; public NinjectControllerFactory() { ninjectKernel = new StandardKernel(); AddBindings(); } private void AddBindings() { ninjectKernel.Bind().To (); } protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType) { return controllerType == null ? null : (IController)ninjectKernel.Get(controllerType); } }
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using System.Web.Routing;namespace WebApplicationNinject{ public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory()); } }}
using Ninject;using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using WebApplicationNinject.Models;namespace WebApplicationNinject.Controllers{ public class StudentController : Controller { IStudent calcImpl; public StudentController(IStudent _calcImpl) { calcImpl = _calcImpl; } // GET: Student public ActionResult Index() { ViewData["test"] = calcImpl.GetName(); return View(); } }}
@{ ViewBag.Title = "Index";}@ViewData["test"]