asp.net mvc 依賴註入Ninject
阿新 • • 發佈:2019-04-30
onf 安裝 inject ext eas ret mvc uget col
1.安裝Ninject
2.使用Ninject
一 安裝Ninject
Nuget:Ninject
二 使用Ninject
public interface IStudent { string GetName(); }
public class Student : IStudent { public string GetName() { return "ligenyun"; } }
public classNinjectControllerFactory : DefaultControllerFactory { private IKernel ninjectKernel; public NinjectControllerFactory() { ninjectKernel = new StandardKernel(); AddBindings(); } private void AddBindings() { ninjectKernel.Bind<IStudent>().To<Student>(); } 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"; } <h2>@ViewData["test"]</h2>
asp.net mvc 依賴註入Ninject