Ninject多个模块

时间:2011-03-06 10:13:19

标签: asp.net-mvc-3 ninject-2

我原本并不认为这会是一个问题,但是当我不断得到例外时,我会发布这里,因为我是个白痴......

我有2个模块类,一个设置NHibernate,一个设置MVC控制器,现在问题是我有类似下面的内容:

public class NHibernateModule : NinjectModule
{
    public override void Load()
    {
        Bind<ISessionManager>().To<SessionManager>();
    }
}

public class ControllerModule : NinjectModule
{
    public override void Load()
    {
        Bind<SomeController>().ToSelf()
                             .WithConstructorArgument("sessionManager", Kernel.Get<ISessionManager>());
    }
}

每当我尝试使用控制器时,它只会炸弹,告诉我它在绑定sessionManager参数时遇到问题。在创建内核时,我确保列表在Controller模块之前有Nhibernate模块。

上面的内容是否有任何直接的愚蠢行为?

1 个答案:

答案 0 :(得分:0)

假设:

public class SomeController : Controller
{
    private readonly ISessionManager _sessionManager;
    public HomeController(ISessionManager sessionManager)
    {
        _sessionManager = sessionManager;
    }

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

以下就足够了:

public class NHibernateModule : NinjectModule
{
    public override void Load()
    {
        Bind<ISessionManager>().To<SessionManager>();
    }
}

public class ControllerModule : NinjectModule
{
    public override void Load()
    {
        Bind<SomeController>().ToSelf();
    }
}

并在Global.asax中:

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",
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

    }

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

    protected override IKernel CreateKernel()
    {
        var modules = new INinjectModule[]
        {
            new NHibernateModule(),
            new ControllerModule()
        };

        return new StandardKernel(modules);
    }
}