Ninject MVC是否应该与MVC 2 Preview一起使用?

时间:2009-09-17 20:33:33

标签: asp.net-mvc ioc-container ninject

我正在运行MVC 2 Preview,这是我第一次尝试使用Ninject2 MVC

我不断得到的错误是: 尝试创建“MyMVC.Controllers.EventsController”类型的控制器时发生错误。确保控制器具有无参数的公共构造函数。

我在Global.cs中拥有的是:

public class MvcApplication : NinjectHttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("elmah.axd");

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

        routes.MapRoute(
            "Root",
            "",
            new { controller = "Home", action = "Index", id = "" }
        );
    }

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

    protected override IKernel CreateKernel()
    {

        return new StandardKernel(new ServiceModule());
    }
}

internal class ServiceModule : NinjectModule
{
    public override void Load()
    {
        Bind<IEventService>().To<EventService>();

        Bind<IEventRepository>().To<EventRepository>();

    }
}

这就是我的控制器的样子。

public class EventsController : Controller
{
    private IEventService _eventService;
    //
    // GET: /Events/

    public EventsController(IEventService eventService)
    {
        _eventService = eventService;
    }
    public ActionResult Index(string name)
    {

        return View(_eventService.GetEvent(name));
    }

    public ActionResult UpcomingEvents()
    {
        return View(_eventService.GetUpcomingEvents().Take(3).ToList());
    }

}

2 个答案:

答案 0 :(得分:1)

我没有使用过Ninject,但我认为你需要实现自己的IControllerFactory。直到他们将其更新为MVC 2.然后使用它而不是RegisterAllControllersIn(..):

ControllerBuilder.Current.SetControllerFactory(new MyNinjectControllerFactory());

编辑:同样,我并不熟悉Ninject,但这可能是一个简单的工厂:

public class MyNinjectControllerFactory : DefaultControllerFactory
{
            protected override IController GetControllerInstance(Type controllerType)
            {
               return [Container].GetInstance(controllerType) as Controller;               
            }
}

答案 1 :(得分:0)

冒着说明问题的风险,您应该尝试向事件控制器添加无参数构造函数。

public class EventsController : Controller
{
    private IEventService _eventService;
    //
    // Parameterless constructor, so NInject will work
    public EventsController() {}
    //
    // Regular constructor
    public EventsController(IEventService eventService)
    {
        _eventService = eventService;
    }