1. 程式人生 > >asp.net mvc 依賴註入Ninject

asp.net mvc 依賴註入Ninject

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 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