0

我正在运行 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());
    }

}
4

2 回答 2

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;               
            }
}
于 2009-09-17T20:40:21.520 回答
0

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

public class EventsController : Controller
{
    private IEventService _eventService;
    //
    // Parameterless constructor, so NInject will work
    public EventsController() {}
    //
    // Regular constructor
    public EventsController(IEventService eventService)
    {
        _eventService = eventService;
    }
于 2009-09-17T20:35:43.620 回答