7

我在dimecasts.net上观看了 Ninject 的前 2 个初学者教程。现在,我想在 ASP.NET MVC 3 中使用 Ninject 2.2。我想要一个带有模拟模型的视图。调用我的服务时,对象引用未设置为对象的实例;

    public class HomeController : Controller
    {
        private readonly IMilestoneService _service;

        public HomeController()
        {
        }

        HomeController(IMilestoneService service)
        {
            _service = service;
        }

        public ActionResult Index()
        {
            ViewBag.Message = "Change Request System";

            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        #region Partial views
        public ActionResult Milestone()
        {
            var result = _service.GetMileStones();//OBJECT REF ERROR
            return View(result);
        }
        #endregion
    }

//####GLOBAL.ASAX
//By using the NinjectHttpApplication, it automatically takes care of controllers, starting up mvc, etc.
//Ninject.Web.Mvc
public class MvcApplication : NinjectHttpApplication
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        //StartNinject();
    }

    #region Inversion of Control

    protected override IKernel CreateKernel()
    {
        return Container;
    }

    static IKernel _container;
    public static IKernel Container
    {
        get
        {
            if (_container == null)
            {
                _container = new StandardKernel(new SiteModule());
            }
            return _container;
        }
    }

    internal class SiteModule : NinjectModule
    {
        public override void Load()
        {
            //Set up ninject bindings here.
            Bind<IMilestoneService>().To<MileStoneService>();
        }
    }
    #endregion
}

我正在使用 Razor,他是里程碑部分视图

@foreach (var item in Model)
{
    <div>item.Name</div>
}

最后,主页视图索引

@{
    ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>
<p>
   @Html.Action("Milestone");
</p>

编辑2013 年 11 月 20 日

请注意,Ninject 已经发布了 2.0 版。这些变化在他们的网站上有很好的概述。值得注意StandardModule的是现在NinjectModule和命名空间Ninject.Core不再存在。我能够用 just 替换它Ninject

4

3 回答 3

16

您的控制器类存在问题,具有依赖项的构造函数是private。您的控制器应如下所示:

public class HomeController : Controller
{
    private readonly IMilestoneService _service;

    public HomeController(IMilestoneService service)
    {
        _service = service;
    }

}

甚至不要包含公共无参数构造函数,它甚至无效,您的类需要该依赖项才能运行。

事实上,我还在构造函数中插入了一个针对该依赖项的空检查,以确保我的类在构造时有效:

public class HomeController : Controller
{
    private readonly IMilestoneService _service;

    public HomeController(IMilestoneService service)
    {
        _service = service;
        Enforce.NotNull(() => _service); // lambda to auto-magically get variable name for exception
    }

}

您的 MvcApplication 类也可能存在问题。

而不是protected void Application_Start(),您可以覆盖不同的功能,protected override void OnApplicationStarted()

这是您对设置路由的调用应该去的地方:

public class MvcApplication : NinjectHttpApplication
{

    public override void Init()
    {
        base.Init();
        Mappers.Initialize();
    }

    protected override Ninject.IKernel CreateKernel()
    {
        return Ioc.Initialize();
    }

    protected override void OnApplicationStarted()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);
    }

    public static void RegisterRoutes(RouteCollection routes) 
    {
        Routing.RegisterRoutes(routes);
        //RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);
    }
}

当然,如果你已经在打电话Application_Start也没关系,但我没有在 OP 中看到它。

于 2011-02-17T17:17:48.483 回答
7

在你的 global.asax 文件中试试这个:

//By using the NinjectHttpApplication, it automatically takes care of controllers, starting up ninject, etc.
//Ninject.Web.Mvc
public class MvcApplication : NinjectHttpApplication
{
    //Your other stuff here. No need to call StartNinject().

    #region Inversion of Control

    protected override IKernel CreateKernel()
    {
        return Container;
    }

    static IKernel _container;
    public static IKernel Container
    {
        get
        {
            if (_container == null)
            {
                _container = new StandardKernel(new SiteModule());
            }
            return _container;
        }
    }

    internal class SiteModule : NinjectModule
    {
        public override void Load()
        {
            //Set up ninject bindings here.
            Bind<IMilestoneService>().To<MileStoneService>();
        }
    }
    #endregion
}
于 2011-02-17T16:44:02.587 回答
4

我相信如果 Ninject 不能绑定那个接口,你会得到一个绑定错误。这让我觉得 Ninject没有实例化你的控制器。

您是否包含了 Ninject.Web.Mvc

于 2011-02-17T16:47:27.873 回答