asp.net mvc 依赖注入Ninject

1.安装Ninject

2.使用Ninject

一 安装Ninject

Nuget:Ninject

asp.net mvc 依赖注入Ninject

二 使用Ninject

asp.net mvc 依赖注入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<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

上一篇:Java 集合转换(数组、List、Set、Map相互转换)


下一篇:cocos2d-x的CCAffineTransform相关变换实现原理