asp.net-mvc - 忍者不开火?

标签 asp.net-mvc dependency-injection inversion-of-control repository ninject

我是第一次尝试设置 Ninject。我有一个 IRepository 接口(interface)和一个 Repository 实现。我正在使用 ASP.NET MVC,并且尝试像这样注入(inject)实现:

public class HomeController : Controller
{
    [Inject] public IRepository<BlogPost> _repo { get; set; }

    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        var b = new BlogPost
                    {
                        Title = "My First Blog Post!",
                        PostedDate = DateTime.Now,
                        Content = "Some text"
                    };

        _repo.Insert(b);

        return View();
    }

    // ... etc
}

这是 Global.asax:

public class MvcApplication : NinjectHttpApplication
{
    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 = "" }  // Parameter defaults
        );

    }

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

    protected override IKernel CreateKernel()
    {
        IKernel kernel = new StandardKernel(new BaseModule());
        return (kernel);
    }
}

这是 BaseModule 类:

   public class BaseModule : StandardModule
    {
        public override void Load()
        {
            Bind<IRepository<BlogPost>>().To<Repository<BlogPost>>();
        }
    }

但是,当我浏览到 Index() 操作时,在尝试使用 _repo.Insert(b) 时收到“对象引用未设置到对象实例”。我遗漏了什么?

最佳答案

Ninject 1.0 没有开箱即用的 MVC 支持。使用 MVC 和 Ninject 1.0 的方法有很多种,分布在网络上。

我建议从 Ninject trunk 获取最新代码,其中包括 MVC 支持。然后使用以下内容作为您的应用程序的起点:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using DemoApp.Models;
using Ninject.Core;
using Ninject.Framework.Mvc;

namespace DemoApp
{
    public class MvcApplication : NinjectHttpApplication
    {
        protected override 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 = "" }  // Parameter defaults
            );
        }

        protected override IKernel CreateKernel()
        {
            return new StandardKernel(new BaseModule(), new AutoControllerModule(Assembly.GetExecutingAssembly()));
        }
    }
}

与您最初的实现相比,有一些事情需要强调......

  • Ninject 有两个 实现名称 NinjectHttpApplication - 一合一 Ninject.Framework.Web 和其中之一 Ninject.Framework.Mvc。你似乎 将前者用作后者 包含 protected RegisterRoutes() 方法。
  • 您需要一种方法让 Ninject Hook 到 Controller 创建中,这是使用 ControllerBuilder 完成的。 Ninject.Framework.Mvc.NinjectHttpApplication 注册 NinjectControllerFactory。如果使用 Ninject 1.0,您必须自己提供它。
  • 您需要向容器注册 Controller 。您可以手动执行此操作,但使用最新的代码提供的 AutoControllerModule 可以自动为您注册 Controller !

关于asp.net-mvc - 忍者不开火?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1230692/

相关文章:

asp.net - 保存数据而不是添加到数据库

java - Guice 中范围注释和范围实例之间的区别

dependency-injection - MVC 4 和 Unity,向 WebAPI Controller 注入(inject)依赖项

mvvm - 为什么在 ViewModelLocator 中将 MEF 用于设计时/运行时?

javascript - 如何解决 ASP.NET 使用子目录时的相对 url 问题?

javascript - JSON发送的数据始终为空

asp.net-mvc - 通过 Nuget 添加后 MVC 6 引用 Jquery

oop - 我们什么时候需要抽象类,如果我们可以使用组合来共享代码,加上接口(interface)来实现多态性?

c# - 结构图 - 同一接口(interface)的两个实现

c# - 在不创建实现的情况下实现接口(interface)(动态代理?)